我该如何更改UIActionSheet按钮的颜色?
iOS 8 (UIAlertController)
如果您正在使用UIAlertController,则非常简单。只需更改UIAlertController视图上的色调颜色即可。
[alertController.view setTintColor:[UIColor red];
iOS 7 (UIActionSheet)
使用这种简单的方法,我成功地更改了文本颜色。
- (void) changeTextColorForUIActionSheet:(UIActionSheet*)actionSheet {
UIColor *tintColor = [UIColor redColor];
NSArray *actionSheetButtons = actionSheet.subviews;
for (int i = 0; [actionSheetButtons count] > i; i++) {
UIView *view = (UIView*)[actionSheetButtons objectAtIndex:i];
if([view isKindOfClass:[UIButton class]]){
UIButton *btn = (UIButton*)view;
[btn setTitleColor:tintColor forState:UIControlStateNormal];
}
}
}
确保在调用之后运行此操作。
[actionSheet showInView];
如果在 [showInView]之前调用它,除了取消按钮外,所有的按钮都将被着色。希望这能帮助到某些人!
https://github.com/gloomcore/UICustomActionSheet
享受它!
很遗憾,如果不使用未记录的API,官方没有提供更改UIActionSheet按钮颜色的正式方法。如果您对UIActionSheet控件进行子类化,则可能可以自定义此功能。
请参考此示例:http://blog.corywiles.com/customizing-uiactionsheet-buttons
UIActionSheet
进行子类化。根据文档:UIActionSheet
不是为了被子类化设计的,也不应该向其层次结构中添加视图。如果您需要呈现一个比 UIActionSheet
API 提供更多自定义的 sheet,您可以创建自己的 sheet 并使用 presentViewController:animated:completion:
模态呈现它。 - memmonsUIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Actionsheet" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
[actionSheet addButtonWithTitle:@"Button 1"]; //Blue color
[actionSheet addButtonWithTitle:@"Button 2"];
[actionSheet addButtonWithTitle:@"Cancel"];
[actionSheet addButtonWithTitle:nil];
[actionSheet setCancelButtonIndex:2];
[actionSheet setDestructiveButtonIndex:1];
[actionSheet showInView:self.view];
UIButton *button = [[actionSheet subviews] objectAtIndex:1];
UIImage *img = [button backgroundImageForState:UIControlStateHighlighted];//[UIImage imageNamed:@"alert_button.png"];
[button setBackgroundImage:img forState:UIControlStateNormal];
您可以通过以下代码轻松实现
苹果公司的
UIActionSheetDelegate
协议文档
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
for (UIView *_currentView in actionSheet.subviews)
{
if ([_currentView isKindOfClass:[UIButton class]])
{
UIButton *button = (UIButton *)_currentView;
[button setTitleColor:YOUR_COLOR forState:UIControlStateNormal];
}
}
}