【问题标题】:How to get first two lines text from UILabel如何从 UILabel 获取前两行文本
【发布时间】:2018-02-16 09:23:09
【问题描述】:

我想从 UIlabel 获取前两行文本。我搜索了很多但没有找到任何解决方案。请告诉我如何获取前两行文本。

【问题讨论】:

  • 请添加您的示例文本和您使用的内容。
  • 就像一个段落中的示例在 UILabel 中设置文本。然后我想从段落中获取前两行。
  • 请问您为什么需要这样做?您基本上是根据 UI 元素的大小来切割字符串,这些元素在不同的设备上会有不同的大小。你想达到什么目标?
  • 当文本大于 2 行时,我基本上是在尝试在 UIlabel 中附加“查看更多...”文本。所以请告诉我如何实现这一点。

标签: ios swift uilabel


【解决方案1】:

使用此扩展程序检查您的标签的行授予者数量是否为 2 或您的目标,然后应用此扩展程序:

extension UILabel {

    func addTrailing(with trailingText: String, moreText: String, moreTextFont: UIFont, moreTextColor: UIColor) {
        let readMoreText: String = trailingText + moreText

        let lengthForVisibleString: Int = self.vissibleTextLength()
        let mutableString: String = self.text!
        let trimmedString: String? = (mutableString as NSString).replacingCharacters(in: NSRange(location: lengthForVisibleString, length: ((self.text?.characters.count)! - lengthForVisibleString)), with: "")
        let readMoreLength: Int = (readMoreText.characters.count)
        let trimmedForReadMore: String = (trimmedString! as NSString).replacingCharacters(in: NSRange(location: ((trimmedString?.characters.count ?? 0) - readMoreLength), length: readMoreLength), with: "") + trailingText
        let answerAttributed = NSMutableAttributedString(string: trimmedForReadMore, attributes: [NSFontAttributeName: self.font])
        let readMoreAttributed = NSMutableAttributedString(string: moreText, attributes: [NSFontAttributeName: moreTextFont, NSForegroundColorAttributeName: moreTextColor])
        answerAttributed.append(readMoreAttributed)
        self.attributedText = answerAttributed
    }

    func vissibleTextLength() -> Int {
        let font: UIFont = self.font
        let mode: NSLineBreakMode = self.lineBreakMode
        let labelWidth: CGFloat = self.frame.size.width
        let labelHeight: CGFloat = self.frame.size.height
        let sizeConstraint = CGSize(width: labelWidth, height: CGFloat.greatestFiniteMagnitude)

        let attributes: [AnyHashable: Any] = [NSFontAttributeName: font]
        let attributedText = NSAttributedString(string: self.text!, attributes: attributes as? [String : Any])
        let boundingRect: CGRect = attributedText.boundingRect(with: sizeConstraint, options: .usesLineFragmentOrigin, context: nil)

        if boundingRect.size.height > labelHeight {
            var index: Int = 0
            var prev: Int = 0
            let characterSet = CharacterSet.whitespacesAndNewlines
            repeat {
                prev = index
                if mode == NSLineBreakMode.byCharWrapping {
                    index += 1
                } else {
                    index = (self.text! as NSString).rangeOfCharacter(from: characterSet, options: [], range: NSRange(location: index + 1, length: self.text!.characters.count - index - 1)).location
                }
            } while index != NSNotFound && index < self.text!.characters.count && (self.text! as NSString).substring(to: index).boundingRect(with: sizeConstraint, options: .usesLineFragmentOrigin, attributes: attributes as? [String : Any], context: nil).size.height <= labelHeight
            return prev
        }
        return self.text!.characters.count
    }
}

统计标签的行数:

func countLabelLines(label: UILabel) -> Int {
        // Call self.layoutIfNeeded() if your view uses auto layout
        self.view.layoutIfNeeded()
        let myText = label.text! as NSString

        let rect = CGSize(width: label.bounds.width, height: CGFloat.greatestFiniteMagnitude)
        let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: label.font], context: nil)

        return Int(ceil(CGFloat(labelSize.height) / label.font.lineHeight))
    }

示例:

if self.countLabelLines(label: lblmedicationDetailText) >= numberOflines{

            let readmoreFont = UIFont(name: "Montserrat-Regular", size: 15.0)
            let readmoreFontColor = UIColor.init(red: 1.0/255.0, green: 100.0/255.0, blue: 157.0/255.0, alpha: 1.0)
            DispatchQueue.main.async {
                self.lblmedicationDetailText.addTrailing(with: "... ", moreText: "Read More", moreTextFont: readmoreFont!, moreTextColor: readmoreFontColor)
            }
        }

【讨论】:

【解决方案2】:
let numOfLine = self.numberOfLinesInLabel(self.testingLabel.text!, labelWidth: self.testingLabel.frame.width, labelHeight: self.testingLabel.frame.height, font: self.testingLabel.font)

self.getNumberOfLineDict.setValue(numOfLine, forKey: String(i))


let Lines : Int = getNumberOfLineDict.valueForKey(String(indexPath.row)) as! Int // I did it in tableview. So I used indexPath.row

if Lines > 2
{
   ReadmoreBtn.isHidden = false
}
else
{
   ReadmoreBtn.isHidden = true
}

获取文本中的行数

 func numberOfLinesInLabel(yourString: String, labelWidth: CGFloat, labelHeight: CGFloat, font: UIFont) -> Int {

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.minimumLineHeight = labelHeight
        paragraphStyle.maximumLineHeight = labelHeight
        paragraphStyle.lineBreakMode = .ByWordWrapping

        let attributes: [String: AnyObject] = [NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle]

        let constrain = CGSizeMake(labelWidth, CGFloat(Float.infinity))

        let size = yourString.sizeWithAttributes(attributes)
        let stringWidth = size.width

        let numberOfLines = ceil(Double(stringWidth/constrain.width))
        return Int(numberOfLines)
  }

【讨论】:

  • 我不想再创建一个 ReadmoreBtn。
  • 好的。使用我的代码,当行数大于 2 时,你可以做任何你想做的事情
【解决方案3】:

我的建议是只在 UI 上做一些事情。 您可以设置一个 UIView(例如它具有逐渐清晰到白色的视图并具有标签“查看更多...”)以覆盖除前两行之外的原始标签。 您可以通过label.font.lineHeight * 2 获取前两行的高度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多