swift中想要动态计算text文字的大小
搜:
swift calculate UItext size
参考:
ios – Calculating UILabel Text Size – Stack Overflow
ios – Adjust UILabel height to text (Swift) – Stack Overflow
搜:
swift calculate UITextView size
参考:
dynamic – How do I size a UITextView to its content on iOS 7? – Stack Overflow
暂时用的是:
//TODO: add support for other device type //current only for iPhone 6 let singleLineMaxWidth = UIScreen.mainScreen().bounds.width * 0.6 print("singleLineMaxWidth=\(singleLineMaxWidth)") let realTextSize = self.displayTextView!.sizeThatFits(CGSize(width: singleLineMaxWidth, height: CGFloat.max)) print("realTextSize=\(realTextSize)")
输出:
singleLineMaxWidth=225.0 realTextSize=(221.5, 88.0)
后来整理出一个函数了:
static func calcRealTextSize(text:String, font:UIFont) -> CGSize { let singleLineMaxWidth = UIScreen.mainScreen().bounds.width * 0.6 print("singleLineMaxWidth=\(singleLineMaxWidth)") let tmpTextView = UITextView(frame: CGRectZero) tmpTextView.font = font tmpTextView.text = text let realTextSize = tmpTextView.sizeThatFits(CGSize(width: singleLineMaxWidth, height: CGFloat.max)) print("calculated realTextSize=\(realTextSize)") return realTextSize }
调用举例:
let text:String = “输入你要测试的内容,可长可短” calcRealTextSize(text, font: UIFont.systemFontOfSize(12))
更多函数可参考:
https://github.com/crifan/crifanLib/tree/master/swift
转载请注明:在路上 » 【已解决】swift中动态计算文字大小