swift - 在 Alertview 中快速创建和自定义 UITextfield

标签 swift uitextfield alert

我正在尝试以编程方式在警报 View 内创建一个限制为 100 个字符的大尺寸文本字段。这是我的代码:

func alertWithTF() {
        let alert = UIAlertController(title: Constants.cancelPopupTitle,
                                      message: Constants.cancelPopupMessage,
                                      preferredStyle: .alert)
        alert.addTextField { (textField) in
            textField.frame = CGRect(x: 20, y: 100, width: 300, height: 80)
            textField.placeholder = "Please enter message"
            textField.borderStyle = UITextField.BorderStyle.line
            textField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
        }
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
            guard let textfield = alert?.textFields?.first else { return }
            let message = textfield.text ?? ""
            print(message)
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        self.present(alert, animated: true, completion: nil)
}

这是我的问题:

  • 我想通过编辑文本字段的框架来修改文本字段的高度,但它似乎不起作用。
  • 我还想设置文本字段的限制字符<= 100,但我找不到方法。

我可以使用任何可能的解决方案吗?感谢您帮助我。

最佳答案

  1. UIAlertController 是不可自定义的。您可以针对这种情况创建自己的alertViewController,然后按照您想要的方式使用UI。

  2. 在您的 addTextfield 中,向 self 提供委托(delegate)

      alert.addTextField { (textField) in
    
        textField.frame = CGRect(x: 20, y: 100, width: 300, height: 80)
        textField.placeholder = "Please enter message"
        textField.borderStyle = UITextField.BorderStyle.line
        textField.delegate = self
        textField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
    }
    

并且您可以使用shouldChangeCharactersIn方法来限制长度

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let maxLimit = 180
let currentString = textField.text!
let newString: String =
    currentString.replacingCharacters(in: range, with: string) as String
return newString.length <= maxLength
}

确保您的 ViewController 符合 UITextFieldDelegate。

class YourViewController: UIViewController, UITextFieldDelegate {

}

关于swift - 在 Alertview 中快速创建和自定义 UITextfield,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59210733/

相关文章:

php - 如何上传数据和字符串到服务器[Swift,Php]

arrays - 无法使用类型为 '[ClassName.StructName]' 的索引下标类型为 'ClassName.StructName' 的值

iOS 文本字段,具有部分安全文本输入类型•••••••••••••••0000

iphone - 使用多个 UITextField 进行验证

ios - 填充所有文本字段时如何启用按钮

javascript - 为什么这个动画功能不起作用?

ios - 键盘启动时显示文本字段

arrays - 将 id 内的数组字符串值与 Swift 3 中的索引匹配

javascript - 如何告诉用户使用浏览器检测在 Chrome 中打开页面

javascript - 在测试使用 qunit 显示的方法时避免/捕获/验证 Javascript 警报