我正在嘗試確定可以容納在恒定大小 textview 中的屬性文本的數量。我嘗試過使用 CTFrameSetter,但我認為這只有在我們已經知道要添加的文本時才有用。到目前為止,我已經嘗試過了
func numberOfCharactersThatFitTextView() -> Int {
let fontRef = CTFontCreateWithName(font!.fontName as CFString, font!.pointSize, nil)
let attributes = [kCTFontAttributeName : fontRef]
let attributedString = NSAttributedString(string: text!, attributes: attributes as [NSAttributedString.Key : Any])
let frameSetterRef = CTFramesetterCreateWithAttributedString(attributedString as CFAttributedString)
var characterFitRange: CFRange = CFRange()
CTFramesetterSuggestFrameSizeWithConstraints(frameSetterRef, CFRangeMake(0, 0), nil, CGSize(width: bounds.size.width, height: bounds.size.height), &characterFitRange)
return Int(characterFitRange.length)
}
uj5u.com熱心網友回復:
編輯
有時候,我想太多了……
如果您只想獲得適合的最大行數,則可以使用字體的.lineHeight屬性:
// the height of your text view
let h: CGFloat = 160.0
// whatever your font is
let font: UIFont = .systemFont(ofSize: 24.0)
let maxLines: Int = Int(floor(h / font.lineHeight))
print("Max Number of Lines:", maxLines)
原答案
如果你想要適合給定 textView 高度的行數,你可以這樣做......
首先,一個方便的擴展:
extension NSAttributedString {
func height(containerWidth: CGFloat) -> CGFloat {
let rect = self.boundingRect(with: CGSize.init(width: containerWidth, height: CGFloat.greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading],
context: nil)
return ceil(rect.size.height)
}
func width(containerHeight: CGFloat) -> CGFloat {
let rect = self.boundingRect(with: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: containerHeight),
options: [.usesLineFragmentOrigin, .usesFontLeading],
context: nil)
return ceil(rect.size.width)
}
}
然后,使用這個函式:
func numberOfLinesThatFit(inHeight height: CGFloat, withFont font: UIFont) -> Int {
let attributes: [NSAttributedString.Key : Any] = [.font : font]
var n: Int = 0
var str: String = "A"
var attStr: NSAttributedString = NSAttributedString(string: str, attributes: attributes)
// width just needs to be greater than one character width
var h: CGFloat = attStr.height(containerWidth: 200.0)
while h < height {
n = 1
str = "\nA"
attStr = NSAttributedString(string: str, attributes: attributes)
h = attStr.height(containerWidth: 200.0)
}
return n
}
并這樣稱呼它:
// whatever your font is
let font: UIFont = .systemFont(ofSize: 24.0)
// the height of your text view
let h: CGFloat = 160.0
let maxLines: Int = numberOfLinesThatFit(inHeight: h, withFont: font)
print("max lines:", maxLines)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/405065.html
標籤:
下一篇:SwiftUI串列選擇不顯示如果我將NavigationLink和.contextMenu添加到串列中。這是一個已知的錯誤?
