承前文如何在iOS的ActionSheet加上圖片,再來記錄一下iOS 7、8改變字體顏色的方法
情境
ActionSheet共有三個Action為Create、Delete、Cancel
Create、Delete字體要是橘色,Cancel則是黑色
1. 舊版UIActionSheet
// ActionSheet程式碼
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet addButtonWithTitle:@"Create"];
[actionSheet addButtonWithTitle:@"Delete"];
[actionSheet addButtonWithTitle:@"Cancel"];
actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
[actionSheet showInView:self.view];
// 變更顏色程式碼
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet {
// set color for each title
for (UIView *subview in actionSheet.subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
UIButton *button = (UIButton *)subview;
if([button.titleLabel.text isEqual:@"Cancel")
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
else
[button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
}
}
}
2. 新版UIActionSheet
// ActionSheet程式碼
UIAlertController * actionSheetNew = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction* create = [UIAlertAction
actionWithTitle:@"Create"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
// do something
}];
UIAlertAction* delete= [UIAlertAction
actionWithTitle:@"Delete"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
// do something
}];
UIAlertAction* cancel= [UIAlertAction
actionWithTitle:@"Cancel"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
// do something
}];
[actionSheetNew addAction:create];
[actionSheetNew addAction:delete];
[actionSheetNew addAction:cancel];
[self presentViewController:actionSheetNew animated:YES completion:nil];
// 變更顏色程式碼
[create setValue:[UIColor orangeColor] forKey:@"titleTextColor"];
[delete setValue:[UIColor orangeColor] forKey:@"titleTextColor"];
[cancel setValue:[UIColor blackColor] forKey:@"titleTextColor"];
另外,如果想要一次改變所有action的字體顏色,可以針對UIAlertController這樣寫
// 變更顏色程式碼(全部action)
actionSheetNew.view.tintColor = [UIColor orangeColor];
參考資料
如何在iOS的ActionSheet加上圖片
1 則留言:
補充一下
setValue:[UIColor orangeColor] forKey:@"titleTextColor"
經測試,iOS8.2會crash 應該是找不到這個key的關係
張貼留言