NSTextField 沒有ios UILabel那么靈活可以自動換行,所有自己寫了個方法,可以寬度自適應(yīng),上代碼
func fitFontSize(maxSize : NSSize = NSSize.zero){
var text = self.stringValue
var newSize = NSSize.zero
self.sizeToFit()
newSize = self.size
var width = newSize.width;
var height = newSize.height;
let characterSize = width/CGFloat(text.count)
if maxSize.width > 0{
if width > maxSize.width{
width = maxSize.width
var count = Int(maxSize.width / characterSize)
var array = text.components(separatedBy: " ")
var newString = ""
var heightCount = 1;
if array.count > 1{
var currentCount = 0
for i in 0..<array.count{
if currentCount + array[i].count > count{
newString += "\n"
heightCount += 1;
currentCount = 0
}
newString += array[i] + " "
currentCount += array[i].count + 1
}
text = newString
}else{
while count < text.count{
text.insert("\n", at: String.Index.init(encodedOffset: count))
count += count + 1
}
}
height = height * CGFloat(heightCount)
}
}
self.stringValue = text
self.size = NSSize(width: width, height: height)
}
傳入固定寬度,自適應(yīng)后的寬度大于固定寬度會自動換行,并調(diào)整高度。
如果對您有用的話請幫我點個贊吧,xi'x