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-01-09 11:12:37 +08:00 · 3905 次点击
    这是一个创建于 3392 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    6 条回复    2015-01-12 16:18:36 +08:00
    dcty
        1
    dcty  
       2015-01-09 13:54:55 +08:00
    行数0,宽度设置一下,sizeToFit应该还能继续用的。
    但是,但是,都swift了,为啥不直接al
    l12ab
        2
    l12ab  
       2015-01-09 18:47:37 +08:00
    ```
    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-01-09 22:10:45 +08:00
    @dcty al 是什么?
    tsinghan
        4
    tsinghan  
    OP
       2015-01-09 22:10:54 +08:00
    @l12ab 我试一下 谢谢
    kofwang
        5
    kofwang  
       2015-01-09 23:03:49 +08:00 via iPhone
    auto layout
    krafttuc
        6
    krafttuc  
       2015-01-12 16:18:36 +08:00
    值得注意的是 `sizeToFit()` 这个方法会直接更改 label 的尺寸。楼主如果只想知道数值,可以用 sizeThatFits,再做定夺。此外,`NSString` 的某个 category 是有类似 sizeXXX 之类的方法的,把字体等参数传进去可以拿到一个估算的尺寸。

    我猜楼主是把 UILabel 放到 UITableViewCell 里后想动态更改 cell 高度?那种场景下 Auto-Layout 或许不会太方便。其他时候 Auto-Layout 可以省去很多力气。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1255 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 17:53 · PVG 01:53 · LAX 10:53 · JFK 13:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.