Проблема с динамическим отображением ярлыка и суффиксом "подробнее" в конце ярлыка - PullRequest
0 голосов
/ 27 мая 2020

Я пытаюсь реализовать следующую идею.

enter image description here

Описание должно отображаться в ячейке tableview с динамическим размером и высотой не более 4 строк. Если он превышает 4 строки, должна быть показана только его часть, заканчивающаяся многоточием, т.е. (...)

Я использовал решение из этой ссылки на переполнение стека

Я получаю вывод, как на следующем экране

enter image description here

Я хочу, чтобы ячейка tableView должна отображать / отображать динамический c размер. Заголовок - это фиксированная 1 строка, а метка описания должна содержать не более 4 строк, если она содержит эти данные и эти данные / текст превышают 4 строки ... тогда мы должны показать (...) в конец этикетки с 4 строками. Пожалуйста, проверьте следующее изображение

enter image description here

Если текст описания содержит данные в одну или две строки, он должен отображать обычный текст, как показано ниже.

enter image description here

Как я могу исправить эту проблему? или есть какой вариант реализовать?

Вот проект

1 Ответ

2 голосов
/ 27 мая 2020

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

enter image description here

Загрузить демонстрационный проект из Здесь

...