Swift(NSTextField|Swift:NSTextField 宽度自适应文字,自动换行)
【Swift(NSTextField|Swift:NSTextField 宽度自适应文字,自动换行)】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.. 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 = https://www.it610.com/article/text
self.size = NSSize(width: width, height: height)
}
传入固定宽度,自适应后的宽度大于固定宽度会自动换行,并调整高度。
如果对您有用的话请帮我点个赞吧,xi'x
推荐阅读
- Swift中willSet和didSet的简述
- Hacking|Hacking with iOS: SwiftUI Edition - SnowSeeker 项目(一)
- LeetCode算法题-11.|LeetCode算法题-11. 盛最多水的容器(Swift)
- iOS-Swift-map|iOS-Swift-map filter reduce、函数式编程
- Swift|Swift ----viewController 中addChildViewController
- SwiftUI|SwiftUI iOS 瀑布流组件之仿CollectionView不规则图文混合(教程含源码)
- Swift高级应用|Swift高级应用 -01
- Swift5.0|Swift5.0 UITexview的基本使用
- Swift7|Swift7 - 循环、函数
- Swift学习笔记(三)Alamofire二次封装