您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

自定義 UIAlertView:調整提示文字的字體與對齊

編輯:iOS 7 技巧

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,不會觸發私有介面的審核問題,可以放心用於正式上架的專案。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved