Здесь я пробовал другое решение. Я создал функцию, которая возвращает вам первые 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
}
Загрузить демонстрационный проект из Здесь