2017-01-25 97 views
1

我想知道是否有方法在UIAlertController的消息中顯示HTML。在UIAlertController消息上顯示HTML

Android有辦法做到這一點,但我找不到在iOS上做同樣的方法。我現在使用Swift 3。

+2

[AlertController中的Html文件可能重複?](http://stackoverflow.com/questions/36361640/html-file-inside-an-alertcontroller) – JAL

+0

'UIAlertController'不支持這種自定義。創建您自己的警報或找到第三方警報。 – rmaddy

+0

謝謝。我創建了一個自定義提醒並且它可以工作(它需要一些樣式調整,但它可以工作) –

回答

1

您可以使用textFields屬性訪問UIAlertController的文本字段。然後,您可以通過設置attributedText來設置包含HTML的屬性字符串。

+0

代碼片段對於您已經很好的答案會非常有幫助。 –

+2

如何訪問文本字段允許您將警報消息更改爲HTML? – rmaddy

+0

@rmaddy,屬性字符串支持HTML標記,所以通過使用那些您可以在標籤內呈現HTML。 – raidfive

0

那麼,隨着rmaddy的消化,我使用ViewController創建了一個自定義警報。

我在StoryBoard中添加了一個ViewController,其透明度爲75%。在它上面,有兩個標籤(警報和信息)和一個按鈕(關閉整個事物)的視圖。在相關聯的類,唯一的代碼將是:

var alertTitle: String? 
var messageContent: String? 

@IBOutlet weak var titleLabel: UILabel! 
@IBOutlet weak var messageLabel: UILabel! 

@IBOutlet weak var AlertView: UIView! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    // Do any additional setup after loading the view. 

    AlertView.layer.cornerRadius = 5.0 

    let attrStr = try! NSAttributedString(
     data: (messageContent?.data(using: String.Encoding.unicode, allowLossyConversion: true)!)!, 
     options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
     documentAttributes: nil) 

    titleLabel.text = alertTitle 

    messageLabel.lineBreakMode = .byWordWrapping 
    messageLabel.numberOfLines = 0 
    messageLabel.attributedText = attrStr 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 





@IBAction func closeButtonTapped(_ sender: Any) { 

    self.dismiss(animated: true, completion: nil) 
} 

基本上,這將接收將顯示爲標題的文本,該消息(這將是HTML)。

要使用視圖控制器,我創建了一個功能,使用此代碼:

func createAlert(title: String, message: String) { 

    let storyBoard = UIStoryboard(name: "Main", bundle: nil) 
    let alert = storyBoard.instantiateViewController(withIdentifier: "alert") as! AlertViewController 

    alert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext 
    alert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve 

    alert.alertTitle = title 
    alert.messageContent = message 

    self.present(alert, animated: true, completion: nil) 
} 

據我所知,它的工作原理。消息看起來像沒有樣式的純HTML文本(所以我需要糾正它),但它做我需要的。

iOS上的Alerts無法顯示HTML內容有點奇怪。我認爲這可能是一個很好的功能。無論如何,感謝rmaddy的這種消化。這比我預料的更容易。