代码之家  ›  专栏  ›  技术社区  ›  zeeple

Swift 3中UIAlertController中的文字换行

  •  6
  • zeeple  · 技术社区  · 8 年前

    我正在swift 3中构建一个测验应用程序,它利用UITableViewController列出问题,我想使用的是一个警报视图来发布问题,并提供各种答案供选择。我有一个巨大的怪癖,就是长答案的字体要小得多,并且通过在答案中间用省略号替换文本来截断。

    如何在AlertView操作中获得文字换行的答案,并保持相同大小的字体?请注意,由于问题字典中有数百个问题,因此在特定字符长度后手动在答案中插入“\n”是不现实的。

    enter image description here

    func showQuestion(questionNum: Int) {
    
            let alertTitle = "Question \(questionNum + 1)"
            let qDict = test[questionNum] as! [String:String]
            let alertMessage = qDict["Question"]
    
            // create the alert
            let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.alert)
    
            // add the actions (buttons)
            if qDict["Option-A"] != "" {
                alert.addAction(UIAlertAction(title: qDict["Option-A"], style: UIAlertActionStyle.default, handler: nil))
            }
    
            if qDict["Option-B"] != "" {
                alert.addAction(UIAlertAction(title: qDict["Option-B"], style: UIAlertActionStyle.default, handler: nil))
            }
    
            if qDict["Option-C"] != "" {
                alert.addAction(UIAlertAction(title: qDict["Option-C"], style: UIAlertActionStyle.default, handler: nil))
            }
    
            if qDict["Option-D"] != "" {
                alert.addAction(UIAlertAction(title: qDict["Option-D"], style: UIAlertActionStyle.default, handler: nil))
            }
    
            if qDict["Option-E"] != "" {
                alert.addAction(UIAlertAction(title: qDict["Option-E"], style: UIAlertActionStyle.default, handler: nil))
            }
            alert.addAction(UIAlertAction(title: "Come back to this one", style: UIAlertActionStyle.destructive, handler: nil))
    
            // show the alert
            self.present(alert, animated: true, completion: nil)
        }
    
    1 回复  |  直到 8 年前
        1
  •  8
  •   Anbu.Karthik    8 年前

      UILabel.appearance(whenContainedInInstancesOf: [UIAlertController.self]).numberOfLines = 0 // change your self what you need
    

    例如

    let alert = UIAlertController(title: title,
                                      message: "dsfdsf",
                                      preferredStyle: UIAlertControllerStyle.alert)
    
        let cancelAction = UIAlertAction(title: "karthik tested for the word wrap text in alert",
                                         style: .cancel, handler: nil)
    
        alert.addAction(cancelAction)
        self.present(alert, animated: true, completion: nil)
    
          // number of lines
          UILabel.appearance(whenContainedInInstancesOf: [UIAlertController.self]).numberOfLines = 0
          // for font
          UILabel.appearance(whenContainedInInstancesOf: [UIAlertController.self]).font = UIFont.systemFont(ofSize: 10.0)
    

    enter image description here