在iOS 7中,我如何更改UIActionSheet中选项的颜色?

10

我在我的应用程序中使用绿色作为“操作颜色”,我希望我的UIActionSheets选项也是绿色的,以保持一致。如何将UIActionSheet选项的颜色从蓝色更改为绿色?

3个回答

28

使用UIActionSheetwillPresentActionSheet委托方法来更改操作表按钮的颜色。

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
    for (UIView *subview in actionSheet.subviews) {
        if ([subview isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)subview;
            button.titleLabel.textColor = [UIColor greenColor];
        }
    }
}

3
这个答案更好。使用委托方法,不仅更简洁,而且以上的答案没有改变取消按钮的颜色。 - LazerLex
由于某些原因,如果您想要更改字体,您必须在更改颜色之前进行操作,否则它将无法正常工作。 - Breno Gazzola
@BrenoGazzola:发生了什么? - Stephen Melvin
当执行 button.titleLabel.textColor = MY_COLOR; button.titleLabel.font = MY_FONT; 时,选项已更改为新字体,但仍保持蓝色和红色。只需将顺序更改为 button.titleLabel.font = MY_FONT; button.titleLabel.textColor = MY_COLOR; 即可解决问题,我得到了新字体和新颜色。 - Breno Gazzola
这很奇怪。您正在运行哪个版本的iOS,以及使用哪个设备/模拟器来运行代码?如果我今晚能够复制这个问题,我将向苹果提交一个错误报告。 - Stephen Melvin
不要忘记为选定状态设置按钮的颜色! 常规按钮在被点击时会使用UIControlStateHighlighted,但取消按钮将使用UIControlStateSelected。 - Rembrandt Q. Einstein

18

你可以像这样做:

// Your code to instantiate the UIActionSheet
UIActionSheet *actionSheet = [[UIActionSheet alloc] init];
// Configure actionSheet

// Iterate through the sub views of the action sheet
for (id actionSheetSubview in actionSheet.subviews) {
    // Change the font color if the sub view is a UIButton
    if ([actionSheetSubview isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton *)actionSheetSubview;
        [button setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor greenColor] forState:UIControlStateSelected];
        [button setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted];

    }
}
如果您打算经常重复使用这段代码,我建议您创建一个UIActionSheet的子类并使用这段代码。

这是否使用了私有API? - Doug Smith
不,这只是访问UIActionSheet的所有子视图并查找按钮。 - Tim
1
当你点击它时,它会变回蓝色。 - Doug Smith
1
你成功让取消按钮工作了吗?我的按钮一直保持之前的颜色。 - CedricSoubrie

0

您可以在AppDelegate的didFinishLaunchingWithOptions方法中使用以下简短的函数轻松更改应用程序的色调颜色。

[[UIView appearance] setTintColor:[UIColor redColor]];

希望能对你有所帮助 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接