最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】swift中动态计算文字大小

Swift crifan 2487浏览 0评论

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中动态计算文字大小

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.206 seconds, using 22.08MB memory