在ios7中,sizeWithFont:现在已弃用。我现在如何在UIFont对象传递到替换方法sizeWithAttributes:?
当前回答
创建一个接受UILabel实例的函数。并返回CGSize
CGSize constraint = CGSizeMake(label.frame.size.width , 2000.0);
// Adjust according to requirement
CGSize size;
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0){
NSRange range = NSMakeRange(0, [label.attributedText length]);
NSDictionary *attributes = [label.attributedText attributesAtIndex:0 effectiveRange:&range];
CGSize boundingBox = [label.text boundingRectWithSize:constraint options: NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
}
else{
size = [label.text sizeWithFont:label.font constrainedToSize:constraint lineBreakMode:label.lineBreakMode];
}
return size;
其他回答
正如@Ayush的回答:
正如你在苹果开发者网站上看到的sizeWithFont,它已被弃用,所以我们需要使用sizeWithAttributes。
好吧,假设在2019+你可能会使用Swift和String而不是Objective-c和NSString,下面是使用预定义字体获取字符串大小的正确方法:
let stringSize = NSString(string: label.text!).size(withAttributes: [.font : UIFont(name: "OpenSans-Regular", size: 15)!])
- (CGSize) sizeWithMyFont:(UIFont *)fontToUse
{
if ([self respondsToSelector:@selector(sizeWithAttributes:)])
{
NSDictionary* attribs = @{NSFontAttributeName:fontToUse};
return ([self sizeWithAttributes:attribs]);
}
return ([self sizeWithFont:fontToUse]);
}
你仍然可以使用sizeWithFont。但是,在iOS >= 7.0中,如果字符串包含开头和结尾空格或结束行\n,则会导致崩溃。
在使用文本之前修剪文本
label.text = [label.text stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
这也适用于sizeWithAttributes和[label sizeToFit]。
此外,当你有nsstringdrawingtextstorage消息发送到deallocated实例在ios7.0设备它处理这个。
CGSize maximumLabelSize = CGSizeMake(label.frame.size.width, FLT_MAX);
CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
float heightUse = expectedLabelSize.height;
boundingRectWithSize:options:attributes:context:
推荐文章
- buildSessionFactory()配置方法在Hibernate中已弃用?
- 在实现API时,我如何避免在块中捕获自我?
- 从另一个应用程序打开设置应用程序
- 如何应用梯度的背景视图的iOS Swift应用程序
- 使用NSURLSession发送POST请求
- 如果用户强制退出,iOS会将我的应用启动到后台吗?
- 如何更改导航栏上“后退”按钮的标题
- 有没有办法从UITableView中移除分隔线?
- 如何在Objective-C中声明类级属性?
- 我如何获得iOS 7默认的蓝色编程?
- 在Objective-C中@property保留,赋值,复制,非原子
- 我如何在NSAttributedString中创建一个可点击的链接?
- 停止UIWebView垂直“弹跳”?
- 对未渲染的视图进行快照,结果是一个空快照
- 如何隐藏iOS状态栏