我为UIAlertController编写了一个扩展(使用Swift 4),它解决了自动布局的布局问题。如果由于UIAlertController布局的未来更改而出现问题,甚至还有回退消息字符串。
import Foundation
extension UIAlertController {
convenience init(title: String?, customView: UIView, fallbackMessage: String?, preferredStyle: UIAlertController.Style) {
let marker = "__CUSTOM_CONTENT_MARKER__"
self.init(title: title, message: marker, preferredStyle: preferredStyle)
if let customContentPlaceholder = self.view.findLabel(withText: marker),
let customContainer = customContentPlaceholder.superview {
customContainer.addSubview(customView)
customView.translatesAutoresizingMaskIntoConstraints = false
customContainer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[customView]-|", options: [], metrics: nil, views: ["customView": customView]))
customContainer.addConstraint(NSLayoutConstraint(item: customContentPlaceholder,
attribute: .top,
relatedBy: .equal,
toItem: customView,
attribute: .top,
multiplier: 1,
constant: 0))
customContainer.addConstraint(NSLayoutConstraint(item: customContentPlaceholder,
attribute: .height,
relatedBy: .equal,
toItem: customView,
attribute: .height,
multiplier: 1,
constant: 0))
customContentPlaceholder.text = ""
} else {
self.message = fallbackMessage
}
}
}
private extension UIView {
func findLabel(withText text: String) -> UILabel? {
if let label = self as? UILabel, label.text == text {
return label
}
for subview in self.subviews {
if let found = subview.findLabel(withText: text) {
return found
}
}
return nil
}
}
以下是使用示例:
let customView = UIView()
customView.translatesAutoresizingMaskIntoConstraints = false
customView.backgroundColor = .red
customView.addConstraint(NSLayoutConstraint(item: customView,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 100))
let alert = UIAlertController(title: "Alert Title",
customView: customView,
fallbackMessage: "This should be a red rectangle",
preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Yay!", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
这将显示类似于以下内容:
![在此输入图片描述](https://istack.dev59.com/QK5jr.webp)
UIAlertController
的限制问题,但无论我如何处理,都不够好。如果你仍然在苦苦挣扎,请看看我创建的 一个库,它可能会有所帮助。它允许您创建具有一堆内置类型的自定义表单。它还可以扩展和重新设计。 - Daniel Saidi