NSTextField 没有ios UILabel那么灵活可以自动换行,所有自己写了个方法,可以宽度自适应,上代码
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)
}
传入固定宽度,自适应后的宽度大于固定宽度会自动换行,并调整高度。
如果对您有用的话请帮我点个赞吧,xi'x