V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
iOS 开发实用技术导航
NSHipster 中文版
http://nshipster.cn/
cocos2d 开源 2D 游戏引擎
http://www.cocos2d-iphone.org/
CocoaPods
http://cocoapods.org/
Google Analytics for Mobile 统计解决方案
http://code.google.com/mobile/analytics/
WWDC
https://developer.apple.com/wwdc/
Design Guides and Resources
https://developer.apple.com/design/
Transcripts of WWDC sessions
http://asciiwwdc.com
Cocoa with Love
http://cocoawithlove.com/
Cocoa Dev Central
http://cocoadevcentral.com/
NSHipster
http://nshipster.com/
Style Guides
Google Objective-C Style Guide
NYTimes Objective-C Style Guide
Useful Tools and Services
Charles Web Debugging Proxy
Smore
tsinghan
V2EX  ›  iDev

swift 语法, 如何 动态计算 UILabel 的高度 ?

  •  
  •   tsinghan · 2015 年 1 月 9 日 · 4550 次点击
    这是一个创建于 4024 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我还以为直接 sizeToFit()就能直接计算了呢。。。

    6 条回复    2015-01-12 16:18:36 +08:00
    dcty
        1
    dcty  
       2015 年 1 月 9 日
    行数0,宽度设置一下,sizeToFit应该还能继续用的。
    但是,但是,都swift了,为啥不直接al
    l12ab
        2
    l12ab  
       2015 年 1 月 9 日
    ```
    var textContent = UILabel()
    textContent.text = "1234569abcdefghjklmn"
    textContent.font = UIFont.systemFontOfSize(16)
    textContent.numberOfLines = 0
    textContent.frame = CGRect(x:15, y:10, width:self.view.bounds.size.width-30, height:100)
    textContent.sizeToFit()
    ```
    tsinghan
        3
    tsinghan  
    OP
       2015 年 1 月 9 日
    @dcty al 是什么?
    tsinghan
        4
    tsinghan  
    OP
       2015 年 1 月 9 日
    @l12ab 我试一下 谢谢
    kofwang
        5
    kofwang  
       2015 年 1 月 9 日 via iPhone
    auto layout
    krafttuc
        6
    krafttuc  
       2015 年 1 月 12 日
    值得注意的是 `sizeToFit()` 这个方法会直接更改 label 的尺寸。楼主如果只想知道数值,可以用 sizeThatFits,再做定夺。此外,`NSString` 的某个 category 是有类似 sizeXXX 之类的方法的,把字体等参数传进去可以拿到一个估算的尺寸。

    我猜楼主是把 UILabel 放到 UITableViewCell 里后想动态更改 cell 高度?那种场景下 Auto-Layout 或许不会太方便。其他时候 Auto-Layout 可以省去很多力气。
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   1103 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 18:34 · PVG 02:34 · LAX 10:34 · JFK 13:34
    ♥ Do have faith in what you're doing.