Изменение цвета кнопки навигации в MFMailComposerViewController на iOS 7
Я пытаюсь изменить цвет текста для кнопок навигации в MFMailComposerViewController, но он не работает, как на iOS 6. В iOS 6 он работал с UIAppearance следующим образом:
// Navigation button
UIBarButtonItem *barButton = [UIBarButtonItem appearance];
NSDictionary *barButtonTitleTextAttributes = @{UITextAttributeTextColor: [UIColor redColor]};
NSDictionary *disabledBarButtonTitleTextAttributes = @{UITextAttributeTextColor: [UIColor grayColor]};
[barButton setTitleTextAttributes:barButtonTitleTextAttributes forState:UIControlStateNormal];
[barButton setTitleTextAttributes:disabledBarButtonTitleTextAttributes forState:UIControlStateDisabled];
[barButton setBackgroundImage:[[UIImage imageNamed:@"btn_appearance"] stretchableImageWithLeftCapWidth:6 topCapHeight:0] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
Но это не работает на iOS 7 и выглядит так:
![enter image description here]()
Я также попытался установить атрибут tintColor
на navigationBar, но это не имеет никакого эффекта:
navigationBar.tintColor = [UIColor redColor];
Есть ли способ изменить цвет текста кнопки навигации в MFMailComposeViewController на iOS 7?
Ответы
Ответ 1
Я использовал это и отлично работал в iOS7 +
MFMailComposeViewController* mailViewController = [[MFMailComposeViewController alloc] init];
mailViewController.mailComposeDelegate = self;
[mailViewController setToRecipients:@[@"[email protected]"]];
[mailViewController.navigationBar setTintColor:[UIColor orangeColor]];
[self presentViewController:mailViewController animated:YES completion:nil];
Ответ 2
Как говорит OemerA - нет способа изменить цвета. Моя проблема заключалась в том, что в UIAppearance я установил цвет фона на синем, чтобы затем "кнопки" больше не были видны. Так как электронная почта на самом деле не является частью вашего приложения, имеет смысл до появления reset появления nag bar до создания почтового композитора. Вот как я это делаю:
// set to normal white
[[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], NSForegroundColorAttributeName, nil]];
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
// set to back to blue with white text
[[UINavigationBar appearance] setBarTintColor:[UIColor blueColor]];
[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
Ответ 3
Если вы установили tintColor на UIWindow, он отлично работает, , впервые представляя MFMailComposerViewController. Похоже, что он теряет информацию tintColor для последующих вызовов.
Примечание: это изменяет оттенок каждого элемента вашего окна.
Ответ 4
Если вы когда-либо проверяете иерархию представлений, созданную с помощью MFMailComposeViewController, вы увидите, что она содержится в экземпляре _UITextEffectsRemoteView. У вас есть нулевой программный доступ к любым подзаголовкам этого, что я предполагаю, потому что они, вероятно, принадлежат отдельному процессу. Эти объекты будут наследовать все, что установлено на разных прокси-серверах UIAppearance (например, фон бара, titleTextAttributes и т.д.), Но не более того.
Протокол UIAppearance не упоминает об этом в документации, но он имеет это в комментариях файла заголовка:
Note for iOS7: On iOS7 the tintColor property has moved to UIView, and now has special inherited behavior described in UIView.h.
This inherited behavior can conflict with the appearance proxy, and therefore tintColor is now disallowed with the appearance proxy.
Итак, конечный результат заключается в том, что, хотя вы можете контролировать большинство аспектов внешнего вида MFMailComposeViewController, вы всегда будете получать синий цвет цвета по умолчанию.
Отчет об ошибке: http://openradar.appspot.com/radar?id=6166546539872256
Ответ 5
Swift 3.0
func sendEmail() {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.navigationBar.tintColor = UIColor.red
mail.mailComposeDelegate = self
mail.setToRecipients(["[email protected]"])
mail.setMessageBody("<p>You're so awesome!</p>", isHTML: true)
present(mail, animated: true)
} else {
// show failure alert
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}
Ответ 6
Как уже указывалось несколько раз, настройка оттенка на панели навигации MFMailComposeViewController не работает. Если у вас есть другие изменения внешнего вида для всего приложения, цвет оттенка - только один аспект проблемы, в нашем приложении мы изменили цвет штриха и размер текста UIBarButton, поэтому в MFMailComposeViewController мы видим следующее:
![Стиль панели навигации в MFMailComposeViewController]()
Внешний вид в нашем приложении установлен в классе StyleGuide с функцией configureAppearanceModifiers
, вызванной из AppDelegate.
Взяв пример из @timosdk, я добавил второй метод:
- (void)neutraliseAppearanceModifiers {
[[UINavigationBar appearance] setTranslucent:NO];
[[UINavigationBar appearance] setTintColor:nil];
[[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
[[UINavigationBar appearance] setBackIndicatorImage:nil];
[[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:nil];
[[UINavigationBar appearance] setBackgroundImage:nil
forBarPosition:UIBarPositionAny
barMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setTitleTextAttributes:nil forState:UIControlStateNormal];
[[UIBarButtonItem appearance] setTitleTextAttributes:nil forState:UIControlStateHighlighted];
[[UIBarButtonItem appearance] setTitleTextAttributes:nil forState:UIControlStateDisabled];
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:nil forState:UIControlStateNormal];
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:nil forState:UIControlStateHighlighted];
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:nil forState:UIControlStateDisabled];
}
Я вызываю это перед инициализацией MFMailComposeViewController, а затем снова вызываю configureAppearanceModifiers
в делегате didFinishWithResult
перед тем, как отклонить ViewController, это отлично работает.