我正试图实现以下想法。
描述应该显示在一个动态大小的tableview单元中,高度不超过4行。如果超过4行,则只显示部分内容,并以省略号结束,即(...)。
我得到的输出结果如下
我想要的是,tableView的单元格必须显示动态大小,标题是固定的1行,描述标签必须最多4行,如果有该数据,并且该数据文本超过4行,那么我们必须显示动态大小。标题是固定的1行,描述标签最多4行,如果它有该数据,并且该数据文本超过4行......那么我们必须显示出 (...) 在标签的末尾有4行。请检查以下图片
如果描述文本包含1或2行数据,它必须显示正常文本,如以下。
我怎样才能解决这个问题呢?
在这里,我已经尝试了不同的解决方案。我已经创建了一个函数,它返回你的前4行的标签在 String
. 然后附加 (...)
在字符串的末尾。
*设置标签的 numberOfLines
到 0
* 假设 leading
和 trailing
标签的空间=20。
func getLinesFromLabel(label:UILabel) -> String? {
let text:NSString = label.text! as NSString
let font:UIFont = label.font
let myFont:CTFont = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil)
let attStr:NSMutableAttributedString = NSMutableAttributedString(string: text as String)
attStr.addAttribute(NSAttributedString.Key(rawValue: String(kCTFontAttributeName)), value:myFont, range: NSMakeRange(0, attStr.length))
let frameSetter:CTFramesetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
let path:CGMutablePath = CGMutablePath()
//set width of label here (i assumed leading and trailing is 20)
path.addRect(CGRect(x:0, y:0, width:UIScreen.main.bounds.width - 50, height:100000))
let frame:CTFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
let lines = CTFrameGetLines(frame) as NSArray
// if lines are more than 4 then return first 4 lines
if lines.count > 4 {
var str = ""
for line in 0..<4 {
let lineRange = CTLineGetStringRange(lines[line] as! CTLine)
let range:NSRange = NSMakeRange(lineRange.location, lineRange.length)
let lineString = text.substring(with: range)
str += lineString
}
let updatedStr = str.suffix(17)
str = String(str.dropLast(17))
let strArr = updatedStr.components(separatedBy: " ")
if strArr.count > 2 {
if strArr[0].count < 5 {
str += strArr[0]
}
}
return str
} else {
return nil
}
}
您的 cellForRowAt
办法
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NoticeListTableViewCell") as! NoticeListTableViewCell
cell.titleLabel.text = titleArray[indexPath.row]
cell.descriptionLabel.text = descriptionArray[indexPath.row]
let readmoreFont = UIFont(name: "Helvetica Neue", size: 16.0)!
let readmoreFontColor = UIColor.blue
let lines = getLinesFromLabel(label: cell.descriptionLabel)
if let first4line = lines {
print(first4line)
let answerAttributed = NSMutableAttributedString(string: first4line, attributes: [NSAttributedString.Key.font: cell.descriptionLabel.font!])
let readMoreAttributed = NSMutableAttributedString(string: " (...)", attributes: [NSAttributedString.Key.font: readmoreFont, NSAttributedString.Key.foregroundColor: readmoreFontColor])
answerAttributed.append(readMoreAttributed)
cell.descriptionLabel.attributedText = answerAttributed
}
return cell
}
下载演示项目 喏