如何限制用户使用 return 的行数?

How to limit the amount of lines a user has using return?

在这个项目中,用户可以写一个字符限制为 150 的 bio。是否也可以限制用户可以拥有的行数?例如,当我在键盘上按 return 时,它会创建一个新行。我可以多次这样做,我可以更改吗?

类似于 Instagram 如何限制生物(高度)的长度,同时仍然有字符限制。

这是字符限制的代码

  // Give textView character limit of 150
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {



        if(textView.text.count > 150 && range.length == 0) {
            print("Opps hit 150")
            navigationItem.rightBarButtonItem?.isEnabled = false

            return false
        }

        navigationItem.rightBarButtonItem?.isEnabled = true

        return true
    }

更新

根据我收到的答复,这是更新后的代码


 var lineCounter = 0


 extension EditProfileController: UITextViewDelegate {

    // Give textView character limit of 150
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

        // Prevent the user from creating to many new lines.


            if(text == "\n") {
                lineCounter += 1
                if lineCounter == 20 {
            }
            print("Stop sending user to next line")
                return false
            }



        if(textView.text.count > 150 && range.length == 0) {
            print("Opps hit 150")
            navigationItem.rightBarButtonItem?.isEnabled = false

            return false
        }

        navigationItem.rightBarButtonItem?.isEnabled = true

        return true
    }

}

所以好消息是,当我单击 return 时,它不会创建新行。但是,是否可以允许 return 按钮在重新运行之前创建 4 个新行 false?

或者,您可以使用一个 class 变量,例如 LineCounter,在您的委托方法中,您应该使用以下代码。它将最大限度地减少您的需求。

//成员变量

var lineCounter = 0

例如,你想要,用户最多可以点击 Return 按钮 5 次,但他可以输入 150 个字符。

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

        if(text == "\n") {
            lineCounter += 1
            if lineCounter >= 5 {

            return false
        }
        }

        if(textView.text.count > 150 && range.length == 0) {
            print("Opps hit 150")
            navigationItem.rightBarButtonItem?.isEnabled = false
            textView.resignFirstResponder()
            return false
        }

        navigationItem.rightBarButtonItem?.isEnabled = true

        return true
    } 

您可以根据字体大小计算 textView 的高度,如果达到该高度则检查 UITextViewDelegate

func textViewShouldEndEditing(_ textView: UITextView) -> Bool { 
    // check here
}