在swift中的Alertview内创建和自定义UITextfield

在swift中的Alertview内创建和自定义UITextfield,swift,uitextfield,alert,Swift,Uitextfield,Alert,我正在尝试在警报视图中创建一个大尺寸的文本字段,编程限制为100个字符。这是我的密码: func alertWithTF() { let alert = UIAlertController(title: Constants.cancelPopupTitle, message: Constants.cancelPopupMessage,

我正在尝试在警报视图中创建一个大尺寸的文本字段,编程限制为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)
}
以下是我的问题:

  • 我想通过编辑文本字段的框架来修改文本字段的高度,但它似乎不起作用
  • 我还想设置textfield的限制字符
  • UIAlertController是不可自定义的。您可以为此情况创建自己的alertViewController,然后根据需要使用UI

  • 在addTextfield中,提供委托给self

      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
    }
    
  • 您可以使用shouldChangeCharacters方法来限制长度

    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
    }
    

    因此,在我自己进行了几次研究之后,我成功地实现了这一点:

    extension ViewController: UITextViewDelegate {
        func alertWithTF() {
            let alert = UIAlertController(title: "Title",
                                          message: "\n\n\n\n\n",
                                          preferredStyle: .alert)
            let textView = UITextView()
            textView.borderColor = .black
            textView.borderWidth = 1.0
            textView.delegate = self
            textView.text = Constants.textViewPlaceholder
            textView.textColor = .lightGray
            alert.view.addSubview(textView)
    
            textView.translatesAutoresizingMaskIntoConstraints = false
            textView.topAnchor.constraint(equalTo: alert.view.topAnchor, constant: 125).isActive = true
            textView.rightAnchor.constraint(equalTo: alert.view.rightAnchor, constant: -20).isActive = true
            textView.leftAnchor.constraint(equalTo: alert.view.leftAnchor, constant: 20).isActive = true
            textView.bottomAnchor.constraint(equalTo: alert.view.bottomAnchor, constant: -60).isActive = true
            textView.heightAnchor.constraint(equalToConstant: 60).isActive = true
    
            alert.view.translatesAutoresizingMaskIntoConstraints = false
    
            alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { [weak self] (_) in
                self?.dismiss(animated: true, completion: nil)
            }))
    
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak self] (_) in
                let message = (textView.text == nil||textView.text == Constants.textViewPlaceholder ? "" : textView.text)
                print(message)
            }))
    
            self.present(alert, animated: true, completion: nil)
        }
    
    因此,我创建了一个TextView而不是TextField,并在alertView中为其设置了约束。这些代码并不完美,但运行良好。我还使用TextView委托处理TextView字符限制和占位符,因为UITextView不支持它:

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
            let numberOfChars = newText.count
            return numberOfChars < 101 //Max 100 chars
        }
    
        func textViewDidBeginEditing(_ textView: UITextView) {
            if textView.textColor == UIColor.lightGray {
                textView.text = ""
                textView.textColor = UIColor.black
            }
        }
    
        func textViewDidEndEditing(_ textView: UITextView) {
            if textView.text == "" {
                textView.text = Constants.textViewPlaceholder
                textView.textColor = UIColor.lightGray
            }
        }
    
    func textView(textView:UITextView,shouldChangeTextIn范围:NSRange,replacementText:String)->Bool{
    让newText=(textView.text作为NSString)。replacingCharacters(在:范围内,使用:text)
    设numberOfChars=newText.count
    返回字符数<101//最多100个字符
    }
    func textViewDidBeginEditing(uTEXTVIEW:UITextView){
    如果textView.textColor==UIColor.lightGray{
    textView.text=“”
    textView.textColor=UIColor.black
    }
    }
    func textViewDidEndEditing(uTEXTVIEW:UITextView){
    如果textView.text==“”{
    textView.text=Constants.textViewPlaceholder
    textView.textColor=UIColor.lightGray
    }
    }
    

    希望这是有帮助的

    关于如何将文本字段限制为一定数量的字符,有很多资源。你找过了吗?另外,如果您最多使用100个字符,那么使用文本视图不是更好吗?大多数参考资料都告诉我使用“shouldChangeCharactersInRange”,但我不太明白它是如何工作的。是的,文本视图似乎更适合这种情况。谢谢你的建议!我知道一开始可能会有点难以承受。我自己也去过那里。关键是要有耐心,多读书。看很多例子。做很多POC。祝你好运谢谢你的详细回答!如果没有可行的解决方案,我将要创建自己的alertViewController。这将文本字段的高度限制为
    100pts
    ,而不是
    textField
    中的字符计数。
    extension ViewController: UITextViewDelegate {
        func alertWithTF() {
            let alert = UIAlertController(title: "Title",
                                          message: "\n\n\n\n\n",
                                          preferredStyle: .alert)
            let textView = UITextView()
            textView.borderColor = .black
            textView.borderWidth = 1.0
            textView.delegate = self
            textView.text = Constants.textViewPlaceholder
            textView.textColor = .lightGray
            alert.view.addSubview(textView)
    
            textView.translatesAutoresizingMaskIntoConstraints = false
            textView.topAnchor.constraint(equalTo: alert.view.topAnchor, constant: 125).isActive = true
            textView.rightAnchor.constraint(equalTo: alert.view.rightAnchor, constant: -20).isActive = true
            textView.leftAnchor.constraint(equalTo: alert.view.leftAnchor, constant: 20).isActive = true
            textView.bottomAnchor.constraint(equalTo: alert.view.bottomAnchor, constant: -60).isActive = true
            textView.heightAnchor.constraint(equalToConstant: 60).isActive = true
    
            alert.view.translatesAutoresizingMaskIntoConstraints = false
    
            alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { [weak self] (_) in
                self?.dismiss(animated: true, completion: nil)
            }))
    
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak self] (_) in
                let message = (textView.text == nil||textView.text == Constants.textViewPlaceholder ? "" : textView.text)
                print(message)
            }))
    
            self.present(alert, animated: true, completion: nil)
        }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
            let numberOfChars = newText.count
            return numberOfChars < 101 //Max 100 chars
        }
    
        func textViewDidBeginEditing(_ textView: UITextView) {
            if textView.textColor == UIColor.lightGray {
                textView.text = ""
                textView.textColor = UIColor.black
            }
        }
    
        func textViewDidEndEditing(_ textView: UITextView) {
            if textView.text == "" {
                textView.text = Constants.textViewPlaceholder
                textView.textColor = UIColor.lightGray
            }
        }