在我的项目中,我使用UIActionSheet
来显示一些排序类型。我想要更改操作表按钮中显示的文本颜色。我们该如何改变文本颜色?
在我的项目中,我使用UIActionSheet
来显示一些排序类型。我想要更改操作表按钮中显示的文本颜色。我们该如何改变文本颜色?
iOS 8: UIActionSheet
已经被弃用。 UIAlertController
会遵循-[UIView tintColor]
,所以以下代码可以使用:
alertController.view.tintColor = [UIColor redColor];
更好的办法是在您的应用程序代理中设置整个窗口的色调颜色:
self.window.tintColor = [UIColor redColor];
iOS 7: 在您的操作表委托中,按照以下方式实现-willPresentActionSheet:
:
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
for (UIView *subview in actionSheet.subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
UIButton *button = (UIButton *)subview;
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}
}
}
iOS 8 中,这些都不再适用。UIActionSheet 文本似乎从 window.tintColor 获取其颜色。
UIAlertViews
和 UIAlertController
显示为 whiteColor
。 - Alex Cio这对我在iOS8上有效
[[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor redColor]];
如果您想查看UIActionSheet
的子视图,应该使用UIButton
的setTitleColor:forState
方法而不是直接设置UILabel
的文本颜色。否则,例如在UIControlEventTouchDragOutside事件发生时,初始颜色将被重置。
以下是正确的方法,重用jrc的代码:
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
for (UIView *subview in actionSheet.subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
UIButton *button = (UIButton *)subview;
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}
}
}
要更改警告操作中特定按钮的颜色,请使用以下方法
let cancelAction = UIAlertAction(title: "Success", style: .cancel, handler: nil)
cancelAction.setValue(UIColor.green, forKey: "titleTextColor")
解决方案适用于 Swift 3。更改所有颜色。
UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).tintColor = .yellow
@jrc的解决方案可以使用,但是当你点击按钮时titleLabel的颜色会发生改变。试试这个方法,使所有状态下的颜色保持一致。
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
UIColor *customTitleColor = [UIColor greenColor];
for (UIView *subview in actionSheet.subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
UIButton *button = (UIButton *)subview;
[button setTitleColor:customTitleColor forState:UIControlStateHighlighted];
[button setTitleColor:customTitleColor forState:UIControlStateNormal];
[button setTitleColor:customTitleColor forState:UIControlStateSelected];
}
}
}
编辑
这里有一个类似的问题: 如何自定义UIActionSheet中的按钮?
尝试使用appearance
协议[无效]
UIButton *btn = [UIButton appearanceWhenContainedIn:[UIActionSheet class], nil];
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
SEL selector = NSSelectorFromString(@"_alertController");
if ([actionSheet respondsToSelector:selector])
{
UIAlertController *alertController = [actionSheet valueForKey:@"_alertController"];
if ([alertController isKindOfClass:[UIAlertController class]])
{
alertController.view.tintColor = [UIColor blueColor];
}
}
else
{
// use other methods for iOS 7 or older.
}