1、代码如下:
import SwiftUI
struct CommentView: View {
@State var comment: String = "这是一个评论,可能会很长,所以需要进行截断。这是一个评论,可能会很长,所以需要进行截断。这是一个评论,可能会很长,所以需要进行截断。这是一个评论,可能会很长,所以需要进行截断。这是一个评论,可能会很长,所以需要进行截断。这是一个评论,可能会很长,所以需要进行截断。这是一个评论,可能会很长,所以需要进行截断。"
@State private var isExpanded: Bool = false
var body: some View {
HStack(alignment: .bottom, spacing: 8) {
Text(comment)
.font(.system(size: 17)) // 使用系统默认字体
.lineLimit(isExpanded ? nil : 4)
.fixedSize(horizontal: false, vertical: true)
if numberOfLines(comment: comment, font: 17) > 4 {
Button(action: {
self.isExpanded.toggle()
}) {
Text(isExpanded ? "收起" : "展开")
.foregroundColor(.blue)
}
}
}
.padding()
}
func numberOfLines(comment: String, font: CGFloat) -> Int {
let lineHeight = calculateLineHeight(for: font) //单行高
let textHeight = comment.heightWithConstrainedWidth(width: UIScreen.main.bounds.width - 32, font: 14)
return Int(textHeight / lineHeight)
}
func calculateLineHeight(for font: CGFloat) -> CGFloat {
let attributedString = NSAttributedString(string: "A", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: font)])
let line = CTLineCreateWithAttributedString(attributedString)
let ascent = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))
return ascent
}
}
// 扩展用于计算文本高度
extension String {
func heightWithConstrainedWidth(width: CGFloat, font: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let customFont = UIFont.systemFont(ofSize: font)// 更改为您希望使用的字体名称和大小
let fontAttributes = [NSAttributedString.Key.font: customFont]
let boundingBox = self.boundingRect(with: constraintRect,
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: fontAttributes as [NSAttributedString.Key : Any], context: nil)
return boundingBox.height
}
}
struct CommentView_Previews: PreviewProvider {
static var previews: some View {
CommentView()
}
}