Swift 4 警报中的 UITextField 最大长度
Swift 4 UITextField max length in Alert
如何在 Alert 中设置 UITextField 的最大长度?
Swift4 中对此的最新最佳实践是什么?
这是我的代码示例,但它会崩溃,因为开始时 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
}
非常感谢您的宝贵时间。
您实际上不需要创建 UITextField
的实例。 addTextField
闭包将为您 return 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()
}
}
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
}
}
您可以将此 class 用于多个文本字段。只需将 class MaxLengthTextField 添加到任何文本字段。然后,您可以从 Storyboard 修改文本字段中的多个字符。 P.s。这是 swift 3.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 [=10=].hasPrefix(" ") {
textField.text = [=10=].trimmingCharacters(in: .whitespaces)
return false
}
return [=10=].count > 0 && [=10=].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
如何在 Alert 中设置 UITextField 的最大长度?
Swift4 中对此的最新最佳实践是什么?
这是我的代码示例,但它会崩溃,因为开始时 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
}
非常感谢您的宝贵时间。
您实际上不需要创建 UITextField
的实例。 addTextField
闭包将为您 return 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()
}
}
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
}
}
您可以将此 class 用于多个文本字段。只需将 class MaxLengthTextField 添加到任何文本字段。然后,您可以从 Storyboard 修改文本字段中的多个字符。 P.s。这是 swift 3.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 [=10=].hasPrefix(" ") {
textField.text = [=10=].trimmingCharacters(in: .whitespaces)
return false
}
return [=10=].count > 0 && [=10=].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