2014-11-06 56 views
1

我正在嘗試更改使用UIAlertController顯示的警報的標題和消息字體 我嘗試使用NSAttributedStirng,但它給出的編譯器錯誤是NSAttributed字符串不能採取替代Stirng 我試過類似this在Swift中使用UIAlertController更改警報的標題和消息字體

var title_attrs = [NSFontAttributeName : CustomFonts.HELVETICA_NEUE_MEDIUM_16] 
var msg_attrs = [NSFontAttributeName : CustomFonts.HELVETICA_NEUE_REGULAR_14] 
var title = NSMutableAttributedString(string:"Done", attributes:title_attrs) 

var msg = NSMutableAttributedString(string:"The job is done ", attributes:msg_attrs) 
let alertController = UIAlertController(title: title, message: title , preferredStyle: UIAlertControllerStyle.Alert) 

有人能指導我怎麼能做到這一點的東西嗎?

回答

3

我認爲Apple從API中刪除了屬性標題和消息。它從來不是公衆的一部分API因此,如果您使用它,蘋果公司不會允許您的應用程序在應用程序商店。

您應該按原樣使用UIAlertController。如果您想對其進行定製,請參閱NSHipster post。如果您想要更多控制,請創建一個自定義視圖來顯示。

1
extension UIAlertController { 
    func changeFont(view:UIView,font:UIFont) { 
     for item in view.subviews { 
      if item.isKindOfClass(UICollectionView) { 
       let col = item as! UICollectionView 
       for row in col.subviews{ 
        changeFont(row, font: font) 
       } 
      } 
      if item.isKindOfClass(UILabel) { 
       let label = item as! UILabel 
       label.font = font 
      }else { 
       changeFont(item, font: font) 
      } 

     } 
    } 
    public override func viewWillLayoutSubviews() { 
     super.viewWillLayoutSubviews() 
     let font = UIFont(name: YourFontName, size: YourFontSize) 
     changeFont(self.view, font: font!) 
    } 
} 
1
let myString = "Alert Title" 
    var myMutableString = NSMutableAttributedString() 
    myMutableString = NSMutableAttributedString(string: myString as String, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!]) 
    myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:0,length:myString.characters.count)) 
    alertController.setValue(myMutableString, forKey: "attributedTitle") 
// and for message 
    alertController.setValue(myMutableString, forKey: "attributedMessage") 
2

斯威夫特3版本:

extension UIAlertController { 
    func changeFont(view: UIView, font:UIFont) { 
     for item in view.subviews { 
      if item.isKind(of: UICollectionView.self) { 
       let col = item as! UICollectionView 
       for row in col.subviews{ 
        changeFont(view: row, font: font) 
       } 
      } 
      if item.isKind(of: UILabel.self) { 
       let label = item as! UILabel 
       label.font = font 
      }else { 
       changeFont(view: item, font: font) 
      } 

     } 
    } 

    open override func viewWillLayoutSubviews() { 
     super.viewWillLayoutSubviews() 
     let font = YOUR_FONT 
     changeFont(view: self.view, font: font!) 
    } 
}