这里有人想要改变特定UIAlertController
中UIAlertAction
个按钮的行为,而不是其他人.(他们希望一个alert 有多行按钮标签,但所有其他alert 的行为正常.)
如果你读UIAlertController
美元的文件,上面写着
UIAlertController类旨在按原样使用,不支持子类化.此类的视图层次 struct 是私有的,不得修改.
作为实验,我决定try 创建一个UIAlertController
的虚拟空子类,这样我就有一个类名可以提供给UI外观方法appearance(whenContainedInInstancesOf:)
虚拟子类的定义如下所示:
class FooController: UIAlertController {
}
这样我就可以使用以下语句
UILabel.appearance(whenContainedInInstancesOf: [FooController.self]).numberOfLines = 2
并特别在FooController
的实例中覆盖UILabel
的外观
它很管用,看起来无懈可击.
您可以从Github here下载样例项目.
当你创建一款香草UIAlertController
时,它的UIAlertAction
个按钮像往常一样有单行标签.当您创建FooController
时,其UIAlertAction
个按钮具有多行标签.
虽然它似乎工作得很完美,但我对苹果公司文档not中子类别UIAlertController
的明确声明持谨慎态度.
忽视这一警告并使用空子类的风险有多大?
以下是我的样例项目中的代码以供参考:
import UIKit
class FooController: UIAlertController {
}
class ViewController: UIViewController {
let buttonLabels = [
"""
Button1
line2
""",
"""
Button2
line2
""",
"""
Button3
line2
"""
]
@IBAction func handleAlertButton(_ sender: Any) {
presentAlert(type: UIAlertController.self)
}
@IBAction func handleFooButton(_ sender: Any) {
presentAlert(type: FooController.self)
}
override func viewDidLoad() {
super.viewDidLoad()
UILabel.appearance(whenContainedInInstancesOf: [FooController.self]).numberOfLines = 2
}
func presentAlert(type: UIAlertController.Type) {
let sheet = type.init(title: type.description(), message: nil, preferredStyle: .actionSheet)
for buttonTitle in buttonLabels {
let item = UIAlertAction(title: buttonTitle, style: .default) { (action) in
print("Button \(buttonTitle) tapped")
}
sheet.addAction(item)
}
present(sheet, animated: true, completion: nil)
}
}