Swift:NSTextField 寬度自適應(yīng)文字,自動換行

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容