- 首先,先放一個正常的
UIAlertController
:
1.現(xiàn)在的title
和message
都是居中對齊的, 但是如果我們想讓他左對齊或者右對齊該怎么做呢, 這里我查UIAlertController
中的屬性并沒有titleLabel
和messageLabel
.說明這兩個label
是隱藏的.外界不能直接訪問的.
2.但是通過找UIAlertController
的subviews
終于找到了
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"物品詳情" message:@"輕便的移動電源很容易就電量耗盡魄幕,而大容量的移動電源往往都比較笨重萝喘,這樣的體驗遠遠比不上直接更換電池。\n對于許多 iPhone 重度使用者來說鳍贾,手機續(xù)航時間不足是一個一直困擾著他們的問題呢岗,當然评汰,從智能手機開始采用不可拆卸電池設(shè)計開始读拆,這個問題就已經(jīng)存在了。在電池技術(shù)沒有突破的情況下纸镊,移動電源成為了解決這個問題的最佳方案倍阐。" preferredStyle:UIAlertControllerStyleAlert];
UIView *subView1 = alertController.view.subviews[0];
UIView *subView2 = subView1.subviews[0];
UIView *subView3 = subView2.subviews[0];
UIView *subView4 = subView3.subviews[0];
UIView *subView5 = subView4.subviews[0];
NSLog(@"%@",subView5.subviews);
//取title和message:
UILabel *title = subView5.subviews[0];
UILabel *message = subView5.subviews[1];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDestructive handler:nil];
[alertController addAction:cancelAction];
[self presentViewController:alertController animated:YES completion:nil];
3.控制臺打印出subView5.subviews
4.這樣我們就可以拿到
titleLabel
和messageLabel
來做設(shè)置了
//比如設(shè)置message內(nèi)容居左:
message.textAlignment = NSTextAlignmentLeft;
title.textAlignment = NSTextAlignmentLeft;
- 但是經(jīng)過嘗試發(fā)現(xiàn),這個可修改的屬性實在是太少了.如果還滿足不了需求怎么辦,比如改變字體顏色,大小等等...,這是可以考慮富文本
1.先看一下效果:
這里我們改變了title
和message
,cancelAction
按鈕的顏色,大小等等.
2.其實很簡單我直接上代碼:
//修改title
NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:@"物品詳情"];
[alertControllerStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
[alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, 2)];
[alertController setValue:alertControllerStr forKey:@"attributedTitle"];
//修改message
NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:@"輕便的移動電源很容易就電量耗盡,而大容量的移動電源往往都比較笨重逗威,這樣的體驗遠遠比不上直接更換電池蔚鸥。"];
[alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, 10)];
[alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(11, 20)];
[alertControllerMessageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(20, 30)];
[alertController setValue:alertControllerMessageStr forKey:@"attributedMessage"];
//修改按鈕的顏色
[cancelAction setValue:[UIColor orangeColor] forKey:@"titleTextColor"];
3.這個方法其實就是通過KVC來實現(xiàn)的.如果不懂得KVC可以看看iOS KVC簡單理和iOS 用KVC來自定義Tabbar,如果不清楚富文本的可以看iOS 富文本.
-
如有錯誤,歡迎雅正