gpt4 book ai didi

ios - 将最大行数设置为 NSMutableAttributedString

转载 作者:行者123 更新时间:2023-11-28 07:36:15 30 4
gpt4 key购买 nike

我正在使用两个 NSMutableAttributedString 并从这两个中创建一个 NSMutableAttributedString。我想限制两个 attributedString 的不同最大行数。我进行了很多搜索,但没有找到有效的选择。

let linkTitleAttributed = NSMutableAttributedString(string: message.getLinkTitle() ?? "" , attributes: [NSFontAttributeName: UIFont.systemFontOfSize(19.0)])
//linkTitleAttributed should be maximum 2 lines.

let linkDescAttributed = NSAttributedString(string: message.getLinkDescription() ?? "", attributes: [NSFontAttributeName: UIFont.systemFontOfSize(15.0)])
//linkDescAttributed should be maximum 5 lines.

let finalAttributed = NSMutableAttributedString()
final.append(linkTitleAttributed)
final.append(linkDescAttributed)

如果文本多于行数,那么它应该以“Lorem Ipsum is simply dummy text...”结尾

我想到了一个解决方案(将文本独立设置为 TextView 并获得可见范围),但我正在寻找更好的解决方案。谢谢。

最佳答案

您必须处理标题和描述的字符串,然后创建一个新的NSAttributedString。像这样的东西:

func limitNumLines(_ msg: String, max: Int) -> String{
if max <= 0 { return "" }

let lines = msg.components(separatedBy: "\n")

var output = ""
for i in 0..<max {
output += lines[i] + "\n"
}
return output
}

let titleMessage = "LINE1\nLINE2\nLINE3\nLINE4"
let descMessage = "line1\nline2\nline3\nline4\nline5\nline6"

//linkTitleAttributed (that is, message) should be maximum 2 lines.
let title = limitNumLines(titleMessage, max: 2)
let linkTitleAttributed = NSMutableAttributedString(string: title , attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 19.0)])

//linkDescAttributed should be maximum 5 lines.
let desc = limitNumLines(descMessage, max: 5)
let linkDescAttributed = NSAttributedString(string: desc , attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15.0)])


let finalAttributed = NSMutableAttributedString()
finalAttributed.append(linkTitleAttributed)
finalAttributed.append(linkDescAttributed)

关于ios - 将最大行数设置为 NSMutableAttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53141943/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com