如何在Alert中设置UITextField的最大长度?
Swift 4中最新的最佳做法是什么?
这是我的代码示例,但它会崩溃,因为UITextField在开始时不存在。
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
let limitLength = 10
@IBOutlet weak var player1: UIButton!
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLength
}
@IBAction func player1Action(_ sender: UIButton) {
let alertController = UIAlertController(title: "Please enter you name", message: "Maximum 10 characters", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {
alert -> Void in
let textField = alertController.textFields![0] as UITextField
// do something with textField
self.player1.setTitle("\(textField.text!)", for: .normal)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alertController.addTextField(configurationHandler: {(textField : UITextField!) -> Void in
textField.placeholder = "Name"
})
self.present(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textField.delegate = self
}
非常感谢你的时间。
答案 0 :(得分:5)
您实际上并不需要创建UITextField
的实例。 addTextField
关闭将为您返回UITextField
。您需要做的就是在闭包中设置该文本字段的委托。
class ViewController: UIViewController, UITextFieldDelegate {
let limitLength = 10
@IBOutlet weak var player1: UIButton!
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLength
}
@IBAction func player1Action(_ sender: UIButton) {
let alertController = UIAlertController(title: "Please enter you name", message: "Maximum 10 characters", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {
alert -> Void in
let textField = alertController.textFields![0] as UITextField
self.player1.setTitle("\(textField.text!)", for: .normal)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alertController.addTextField(configurationHandler: {(textField : UITextField!) -> Void in
textField.placeholder = "Name"
textField.delegate = self // Set the delegate
})
present(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
答案 1 :(得分:1)
class MaxLengthTextField: UITextField, UITextFieldDelegate {
private var characterLimit: Int?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
}
@IBInspectable var maxLength: Int {
get {
guard let length = characterLimit else {
return Int.max
}
return length
}
set {
characterLimit = newValue
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard string.characters.count > 0 else {
return true
}
let currentText = textField.text ?? ""
let prospectiveText = (currentText as NSString).replacingCharacters(in: range, with: string)
// 1. Here's the first change...
return allowedIntoTextField(text: prospectiveText)
}
// 2. ...and here's the second!
func allowedIntoTextField(text: String) -> Bool {
return text.characters.count <= maxLength
}
}
您可以将此类用于多个文本字段。只需将类MaxLengthTextField添加到任何文本字段。然后,您可以从Storyboard中修改文本字段中的多个字符。附:这是swift 3.0
答案 2 :(得分:0)
您可以使用一些Rx函数来管理它,诸如此类
let doneAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: { _ in
block?(alert.textFields?.first?.text)
})
alert.addAction(doneAction)
alert.addTextField { textField in
textField.autocapitalizationType = .sentences
textField.placeholder = NSLocalizedString("Placeholder", comment: "")
textField.rx.text.orEmpty.map {
if $0.hasPrefix(" ") {
textField.text = $0.trimmingCharacters(in: .whitespaces)
return false
}
return $0.count > 0 && $0.count < 30
}.share(replay: 1).bind(to: doneAction.rx.isEnabled).disposed(by: self.disposeBag)
}
在这里,我将文本字段与警报的OK按钮相连,如果文本以空格开头,长度= 0和最大长度= 30,请使用Rx禁用按钮。不要忘记初始化disposeBag,它必须是全局的>
private var disposeBag: DisposeBag = DisposeBag()
并导入
import RxSwift
import RxCocoa