ios 自动缩小字体,如何在iOS 7.0或更高版本中获得自动调整的字体大小?

I want to get the font size of some text after it's been scaled down in a UILabel or UITextField. This was possible before iOS 7.0: How to get UILabel (UITextView) auto adjusted font size?. However, sizeWithFont has been deprecated in iOS 7.0. I've tried using its replacement, sizeWithAttributes, but with no success. Is there any way to do this in iOS 7.0?

解决方案

Here's a function I made to get the adjusted font size of a UILabel:

Swift

func getApproximateAdjustedFontSizeWithLabel(label: UILabel) -> CGFloat {

if label.adjustsFontSizeToFitWidth == true {

var currentFont: UIFont = label.font

let originalFontSize = currentFont.pointSize

var currentSize: CGSize = (label.text! as NSString).sizeWithAttributes([NSFontAttributeName: currentFont])

while currentSize.width > label.frame.size.width && currentFont.pointSize > (originalFontSize * label.minimumScaleFactor) {

currentFont = currentFont.fontWithSize(currentFont.pointSize - 1)

currentSize = (label.text! as NSString).sizeWithAttributes([NSFontAttributeName: currentFont])

}

return currentFont.pointSize

}

else {

return label.font.pointSize

}

}

Objective-C

- (CGFloat)getApproximateAdjustedFontSizeWithLabel:(UILabel *)label {

if (label.adjustsFontSizeToFitWidth) {

UIFont *currentFont = label.font;

CGFloat originalFontSize = currentFont.pointSize;

CGSize currentSize = [label.text sizeWithAttributes:@{NSFontAttributeName : currentFont}];

while (currentSize.width > label.frame.size.width && currentFont.pointSize > (originalFontSize * label.minimumScaleFactor)) {

currentFont = [currentFont fontWithSize:currentFont.pointSize - 1];

currentSize = [label.text sizeWithAttributes:@{NSFontAttributeName : currentFont}];

}

return currentFont.pointSize;

}

else {

return label.font.pointSize;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值