UIAlertView 很少有客製需求,多數情況用系統樣式就好。但有時設計稿會要求調整字體、字級或對齊方式,這時就必須自行介入。
做法是在 view controller 的委派方法 willPresentAlertView: 中遍歷 UIAlertView 的所有 subview,找出對應的 UILabel 後修改其屬性。整體邏輯與客製 UIActionSheet 一致。
- (void)willPresentAlertView:(UIAlertView *)alertView {
// 遍歷 UIAlertView 包含的所有子視圖
for (UIView *tempView in alertView.subviews) {
if ([tempView isKindOfClass:[UILabel class]]) {
UILabel *tempLabel = (UILabel *) tempView;
// 以文字內容比對,確認是訊息本文而非標題
if ([tempLabel.text isEqualToString:alertView.message]) {
// 調整對齊方式
tempLabel.textAlignment = UITextAlignmentLeft;
// 調整字級
[tempLabel setFont:[UIFont systemFontOfSize:15.0]];
}
}
}
}
兩個關鍵點:一是用 isKindOfClass: 做型別檢查,避免對非 UILabel 的視圖送出錯誤訊息;二是透過文字內容比對 alertView.message,把標題與本文的 label 區分開來,只改動需要的那一個。
這段寫法全程使用公開 API,不會觸發私有介面的審核問題,可以放心用於正式上架的專案。