gpt4 book ai didi

ios - 阅读/查看标签末尾的更多信息

转载 作者:搜寻专家 更新时间:2023-10-31 21:46:37 26 4
gpt4 key购买 nike

我正在尝试在我的标签末尾创建一个阅读更多按钮。我希望它默认显示 3 行。我正在用 swift 而不是 objective c 编写代码。只有当用户点击标签的阅读更多部分时,标签才会展开。它的外观和工作方式应该与在 Instagram 上完全一样,但在 Instagram 上除外,它位于表格 View 单元格中。我的标签和阅读更多按钮将在 ScrollView 中。我设法通过调整标签的行数属性来使扩展和收缩部分工作。

if descriptionLabel.numberOfLines == 0{
descriptionLabel.numberOfLines = 3
}else {
descriptionLabel.numberOfLines = 0
}
descriptionLabel.lineBreakMode = NSLineBreakMode.byWordWrapping

我在标签末尾放置“...more”并在正确位置截断文本时遇到问题。我看过其他人对类似问题的回答,但似乎没有任何效果。

我可以在最后一行文本上放置一个按钮,这样让标签的更多部分可点击也不是问题。我遇到的问题是在正确的位置截断文本并将查看更多文本放在正确的位置以便显示。

我还希望阅读更多按钮仅在必要时出现。当只有 1-3 行文本时,我不希望它出现。这也是我遇到的问题。

我不能使用这个 https://github.com/apploft/ExpandableLabel因为它不支持 ScrollView ,只支持表格 View 。

此处的快速解决方案无效:Add "...Read More" to the end of UILabel .它使应用程序崩溃了。

最后,阅读更多按钮应与最后一行文本对齐并位于其末尾。如果它也适用于 tableview 单元格,那将是一个额外的好处!

最佳答案

我找到了 ReadMoreTextView在 Github 中,它基于 UITextView。该库中的关键方法如下:

private func characterIndexBeforeTrim(range rangeThatFits: NSRange) -> Int {
if let text = attributedReadMoreText {
let readMoreBoundingRect = attributedReadMoreText(text: text, boundingRectThatFits: textContainer.size)
let lastCharacterRect = layoutManager.boundingRectForCharacterRange(range: NSMakeRange(NSMaxRange(rangeThatFits)-1, 1), inTextContainer: textContainer)
var point = lastCharacterRect.origin
point.x = textContainer.size.width - ceil(readMoreBoundingRect.size.width)
let glyphIndex = layoutManager.glyphIndex(for: point, in: textContainer, fractionOfDistanceThroughGlyph: nil)
let characterIndex = layoutManager.characterIndexForGlyph(at: glyphIndex)
return characterIndex - 1
} else {
return NSMaxRange(rangeThatFits) - readMoreText!.length
}
}

要显示像“xxxx...Read More”这样的文本,图书馆

  1. 获取 UITextView 中可以显示多少个字符:使用 NSLayoutManager.characterRange(forGlyphRange:, actualGlyphRange:)
  2. 获取最后一个可见字符的位置和“...阅读更多”的宽度:使用 NSLayoutManager.boundingRect(forGlyphRange glyphRange: NSRange, in container: NSTextContainer)
  3. 获取裁剪前的字符索引:使用NSLayoutManager.characterIndexForGlyph(at glyphIndex: Int)
  4. 替换应该用“...Read More”修剪的文本:UITextStorage.replaceCharacters(范围:NSRange,带有 attrString:NSAttributedString)

关于ios - 阅读/查看标签末尾的更多信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46476018/

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