Ios 如何避免swift中出现太多新行
我使用文本视图为用户输入内容,但我无法限制用户点击enter键创建新行的次数,如何将文本视图最多限制为2行 例如: 当前Ios 如何避免swift中出现太多新行,ios,swift,textview,Ios,Swift,Textview,我使用文本视图为用户输入内容,但我无法限制用户点击enter键创建新行的次数,如何将文本视图最多限制为2行 例如: 当前 "Start end" 期望的: "limit 2 empty lines" 您可以将视图控制器设置为文本视图的代理,并使用replacingOccurrences将4行或更多新行替换为3行新行,您还需要避免在字符串开头出现新行: class ViewController: UIViewController, UITextViewDelegate {
"Start
end"
期望的:
"limit
2
empty lines"
您可以将视图控制器设置为文本视图的代理,并使用replacingOccurrences将4行或更多新行替换为3行新行,您还需要避免在字符串开头出现新行:
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
}
func textViewDidChange(_ textView: UITextView) {
// avoid new lines also at the beginning
textView.text = textView.text.replacingOccurrences(of: "^\n", with: "", options: .regularExpression)
// avoids 4 or more new lines after some text
textView.text = textView.text.replacingOccurrences(of: "\n{4,}", with: "\n\n\n", options: .regularExpression)
}
}
您可以将视图控制器设置为文本视图的代理,并使用replacingOccurrences将4行或更多新行替换为3行新行,您还需要避免在字符串开头出现新行:
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
}
func textViewDidChange(_ textView: UITextView) {
// avoid new lines also at the beginning
textView.text = textView.text.replacingOccurrences(of: "^\n", with: "", options: .regularExpression)
// avoids 4 or more new lines after some text
textView.text = textView.text.replacingOccurrences(of: "\n{4,}", with: "\n\n\n", options: .regularExpression)
}
}
那有助于感谢老板那有助于感谢老板