在iPhone上,UIAlertView已经被弃用,因此您应该使用UIAlertController来实现类似的功能。要在UIAlertController中添加UITextField,您需要执行以下步骤:
import UIKit
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
let textField = UITextField()
alertController.addTextField { (textField) in
textField.placeholder = "Enter text here"
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
完整的代码示例:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.center = view.center
button.setTitle("Show Alert", for: .normal)
button.addTarget(self, action: #selector(showAlert), for: .touchUpInside)
view.addSubview(button)
}
@objc func showAlert() {
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
let textField = UITextField()
alertController.addTextField { (textField) in
textField.placeholder = "Enter text here"
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
这段代码将在屏幕中央创建一个按钮,当用户点击该按钮时,将显示一个包含UITextField的UIAlertController。
领取专属 10元无门槛券
手把手带您无忧上云