Autoshrink on a UILabel with multiple lines

前端 未结 17 2050
醉梦人生
醉梦人生 2020-11-28 21:31

Is it possible to use the autoshrink property in conjunction on multiple lines on a UILabel? for example, the large text size possible on 2 available lines.

17条回答
  •  佛祖请我去吃肉
    2020-11-28 22:15

    There is a method on NSString, -sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode: which has apparently existed since iOS 2.0, but unfortunately is deprecated in iOS 7 without a suggested alternative as the automatic reduction of font size is discouraged. I don't really understand Apple's stance on this as they use it in keynote etc and I think if the font sizes are within a small range it is ok. Here's an implementation in Swift using this method.

    var newFontSize: CGFloat = 30
        let font = UIFont.systemFontOfSize(newFontSize)
        (self.label.text as NSString).sizeWithFont(font, minFontSize: 20, actualFontSize: &newFontSize, forWidth: self.label.frame.size.width, lineBreakMode: NSLineBreakMode.ByWordWrapping)
        self.label.font = font.fontWithSize(newFontSize)
    

    I'm not aware of a way this can be achieved without using deprecated methods.

提交回复
热议问题