【问题标题】:Get number of lines UITextView without using "\n"?在不使用“\n”的情况下获取 UITextView 的行数?
【发布时间】:2015-04-22 07:42:44
【问题描述】:

我有一个 textView,我需要它的行数,或者 sizeToFit 在它变为 sizeToFit 之前。我试过在 textView 中检查换行符“\n”的数量。但是,textView 中的文本已被解析,因为它来自服务器非常混乱,有大量的 html 代码和糟糕的换行符,我不得不使用 replaceOccurence of "\n" 来删除换行符以使文本成为一个不错的段落。

var rawString = self.selectedProduct.description   
var cleanString = rawString?.stringByReplacingOccurrencesOfString("\n", withString: " ", options: NSStringCompareOptions.LiteralSearch, range: nil)

这段代码当然只会在上面的代码之后返回1。

let desString = self.descriptionTextView.text
let numLines = desString.componentsSeparatedByString("\n")
println(numLines.count)

此代码崩溃。

 let numLines = self.descriptionTextView.contentSize.height / self.descriptionTextView.font.leading

最终,我想要部分显示文本并有一个显示所有文本的按钮。

谢谢

【问题讨论】:

  • numLines = textView.contentSize.height/textView.font.lineHeight 请检查一下
  • 你也可以查一下。 UIFont *font = [UIFont boldSystemFontOfSize:11.0]; CGSize size = [string sizeWithFont:font constrainedToSize:myUITextView.frame.size lineBreakMode:UILineBreakModeWordWrap]; // 默认模式 float numberOfLines = size.height / font.lineHeight;
  • 有趣。您的第一个解决方案因“发现 nil 展开可选值”错误而崩溃......它每次都会给出 3.0XX 的小数。我很难使用 swift 的第二个解决方案。
  • @TuanAnhVu 那是因为 sizeWithFont 已贬值。 sizeWithAttributes 是替代品。

标签: ios swift uitextview


【解决方案1】:

我已将@aBilal17 的评论转换为非贬值的东西,而且很快。

// This gives you the size of that string

let font = UIFont.systemFontOfSize(11)
let style = NSMutableParagraphStyle()
style.lineBreakMode = NSLineBreakMode.ByWordWrapping
let size = someString.sizeWithAttributes([NSFontAttributeName: font, NSParagraphStyleAttributeName: style])

我使用这个扩展来获得限制宽度的字符串的大小:

extension String {
    func sizeForWidth(width: CGFloat, font: UIFont) -> CGSize {
        let attr = [NSFontAttributeName: font]
        let height = NSString(string: self).boundingRectWithSize(CGSize(width: width, height: CGFloat.max), options:.UsesLineFragmentOrigin, attributes: attr, context: nil).height
        return CGSize(width, ceil(height))
    }
}

所以你可以这样做:

let numLines = desString.sizeForWidth(descriptionTextView.contentSize.width, font: descriptionTextView.font).height / descriptionTextView.font.lineHeight

【讨论】:

  • 谢谢!但我收到“无法以样式分配 LineBreakMode”错误。当我注释掉 style.lineBreakMode = NSLineBreakMode.ByWordWrapping 时,无论我有多少文本,我的 size.height 每次都等于 13.123。
  • 我在操场上做过这样的事情,它可以工作:let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 200, height: 100)) textView.text = "AAds asd adasdasd asd assa sss asasas asasdd ddd dass asdasd asdasd" let numLines = Int(textView.text.sizeForWidth(textView.contentSize.width, font: textView.font).height / textView.font.lineHeight)
  • 很高兴能帮到你:)
猜你喜欢
  • 2015-10-18
  • 2018-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-03
  • 2013-05-06
  • 2021-08-12
  • 1970-01-01
相关资源
最近更新 更多