UITEXTVIEW-每行字符的限制数量

发布于 2025-01-26 12:41:39 字数 168 浏览 1 评论 0原文

我有一个uitextView,每次用户每行限制chars限制时,我都想划分(假设每行30个字符是最大的字符)。而且我也想保存单词包装,因此,如果单词中间达到了30个限制,则应该直接进入新行。

我应该如何解决这个问题?我希望有一个本机解决方案,但在文档中找不到任何相关的解决方案。

I have a UITextView and I want to line break each time a user is extending a limit of chars per line (let's say 30 chars per line is the maximum). And I want to save the word wrapping too so if a 30 limit is reached in the middle of a word, it should just go straight to the new line.

How should I approach this problem? I was hoping for a native solution but can't find anything related in the documentation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酷炫老祖宗 2025-02-02 12:41:39

您可以使用textViewDidchangeuitextviewDelegate使用textViewDidChange委托方法来添加newline,每30个字符之后,

func textViewDidChange(_ textView: UITextView) {
    if let text = textView.text {
        let strings = string.components(withMaxLength: 30) // generating an array of strings with equally split parts
        var newString = ""
        for string in strings {
            newString += "\(string)\n" //joining all the strings back with newline
        }
       textView.text = String(newString.dropLast(2)) //dropping the new line sequence at the end
    }
}

您将需要此扩展名来split string> string 在上述代码中相等的部分工作:

extension String {
    func components(withMaxLength length: Int) -> [String] {
        return stride(from: 0, to: self.count, by: length).map {
            let start = self.index(self.startIndex, offsetBy: $0)
            let end = self.index(start, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
            return String(self[start..<end])
        }
    }
}

You can use this workaround by using textViewDidChange delegate method from UITextViewDelegate to add newline after every 30 characters, like this

func textViewDidChange(_ textView: UITextView) {
    if let text = textView.text {
        let strings = string.components(withMaxLength: 30) // generating an array of strings with equally split parts
        var newString = ""
        for string in strings {
            newString += "\(string)\n" //joining all the strings back with newline
        }
       textView.text = String(newString.dropLast(2)) //dropping the new line sequence at the end
    }
}

You will need this extension to split String in equal parts for above code to work though:

extension String {
    func components(withMaxLength length: Int) -> [String] {
        return stride(from: 0, to: self.count, by: length).map {
            let start = self.index(self.startIndex, offsetBy: $0)
            let end = self.index(start, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
            return String(self[start..<end])
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文