美文网首页
ios marsonly文字的显示全文和收起

ios marsonly文字的显示全文和收起

作者: 授之以渔不如授之以鱼 | 来源:发表于2021-03-04 11:00 被阅读0次

    先设置文字宽度

            self.descritionLabel.preferredMaxLayoutWidth = kScreenWidth - 80 - 16
    

    才能获取正确的文字行数,根据行数显示或隐藏按钮

             self.showButton.isHidden = descritionLabel.totalOfLines() <= 3 ? true : false
    

    如果有按钮,点击按钮设置状态user.isExpand,根据状态来展开收起文字

                self.descritionLabel.numberOfLines = user.isExpand == true ? 0 : 3
    

    extension获得label总行数

      /// - Returns: 总行数
        func totalOfLines() -> Int {
            
            if let attrText = self.attributedText {
                
                /// 创建CTFrame
                let setter: CTFramesetter = CTFramesetterCreateWithAttributedString(attrText)
                let path: CGMutablePath = CGMutablePath()
                path.addRect(CGRect(x: 0, y: 0, width: self.preferredMaxLayoutWidth, height: CGFloat.greatestFiniteMagnitude))
                let frame: CTFrame = CTFramesetterCreateFrame(setter, CFRangeMake(0, 0), path, nil)
                
                /// 获得CTLine数组
                let lines = CTFrameGetLines(frame)
                
                //获得行数
                let totalOfLines = CFArrayGetCount(lines)
                //Logger.log("totalOfLines: \(totalOfLines) :\(attrText.string)")
                return totalOfLines
            }
         
            return 0
        }
    

    相关文章

      网友评论

          本文标题:ios marsonly文字的显示全文和收起

          本文链接:https://www.haomeiwen.com/subject/fkohqltx.html