gpt4 book ai didi

Swift:字符串 - 计算高度的第一个字符位置?

转载 作者:行者123 更新时间:2023-11-28 13:46:36 24 4
gpt4 key购买 nike

我想缩短长字符串以“查看更多...”结尾

如果字符串没有新行,一切顺利。


"The cat ate the cake and went outside the house, without any problems. Then the next day something really bad happened. The owner kicked the cat out, and the little animal had no chance to go back."

成为

"The cat ate the cake and went outside the house, without any problems. Then the see more..."


但除此之外,我也想限制高度。这样字符串的高度最大为 200pt,如下所示:

2 new lines

>

1 new line

3 new lines

>

>

0 new line

应该变成

2 new lines

>

1 new line

See more...


我如何确定应该在哪个字符后放置“查看更多...”文本?

代码:

func shorten(maxWidth : CGFloat) -> NSMutableAttributedString {


let font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
// If height is more than 200pt
if self.height(withConstrainedWidth: maxWidth, font: font) > 200 {
// Here.. how?
return finalString
}

// If char is more than 400
if self.count > 400 {
// BLA BLA CUT TEXT
return finalString
}

let finalString = NSMutableAttributedString(string: self, attributes: [NSAttributedString.Key.font : font])

return finalString
}

最佳答案

我强烈建议您不要将 see more... 作为纯字符串放在您的文本中。

更好的方法是在 UIButton 标签后立即添加 see more... 文本。

在这种情况下,您可以轻松地操纵它的位置、形式、UI 等

关于Swift:字符串 - 计算高度的第一个字符位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55328215/

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