2017-10-05 86 views
0

我試圖將UILabel添加到AlertController中,但它不能在Alert上顯示。 我可以使它成爲UIImageView,但我不能用於UILabel。這下面是我的代碼片段如何將UILabel添加到UIAlertController中

let alert = UIAlertController(title: meta.name!, message: "", preferredStyle: .alert) 
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) 
    var sizeLabel = UILabel(frame: CGRect(x: 10, y: 10, width: 50, height: 50)) 
    sizeLabel.numberOfLines = 0 
    sizeLabel.lineBreakMode = .byWordWrapping 
    sizeLabel.sizeToFit() 
    sizeLabel.preferredMaxLayoutWidth = alert.view.frame.size.width 
    sizeLabel.font = UIFont(name: "Avenir-Light", size: 20) 
    sizeLabel.text = "Hello IOS" 

    alert.view.addSubview(sizeLabel) 
+0

見https://stackoverflow.com/a/44050057/8722754 – CodeNinja

+0

我想它已經和我的代碼非常相似也。但它不起作用。它永遠不會顯示我的標籤 – StxApp

回答

0

因此,一些快速研究後,它看起來就像你不能直接將標籤添加到UIAlertController。但是,您可以使用AttributedStrings。我使用的答案從https://stackoverflow.com/a/30661824/8722754我的靈感和更新,以斯威夫特3:

let attributedString = NSAttributedString(string: "My Message", 
     attributes: [NSAttributedStringKey.font : UIFont(name: "Avenir-Light", size: 20)!]) 

    let alert = UIAlertController(title: "Title", message: "", preferredStyle: .alert) 

    alert.setValue(attributedString, forKey: "attributedMessage") 

    let cancelAction = UIAlertAction(title: "OK", style: .default, handler: nil) 

    alert.addAction(cancelAction) 

    present(alert, animated: true, completion: nil) 
相關問題