在ios7中,sizeWithFont:现在已弃用。我现在如何在UIFont对象传递到替换方法sizeWithAttributes:?
当前回答
基于@bitsand,这是一个新方法,我刚刚添加到我的NSString+Extras类别:
- (CGRect) boundingRectWithFont:(UIFont *) font constrainedToSize:(CGSize) constraintSize lineBreakMode:(NSLineBreakMode) lineBreakMode;
{
// set paragraph style
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:lineBreakMode];
// make dictionary of attributes with paragraph style
NSDictionary *sizeAttributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName: style};
CGRect frame = [self boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:sizeAttributes context:nil];
/*
// OLD
CGSize stringSize = [self sizeWithFont:font
constrainedToSize:constraintSize
lineBreakMode:lineBreakMode];
// OLD
*/
return frame;
}
我只是使用结果帧的大小。
其他回答
我创建了一个类别来处理这个问题,它是:
#import "NSString+StringSizeWithFont.h"
@implementation NSString (StringSizeWithFont)
- (CGSize) sizeWithMyFont:(UIFont *)fontToUse
{
if ([self respondsToSelector:@selector(sizeWithAttributes:)])
{
NSDictionary* attribs = @{NSFontAttributeName:fontToUse};
return ([self sizeWithAttributes:attribs]);
}
return ([self sizeWithFont:fontToUse]);
}
这样你只需要找到/替换sizeWithFont: sizeWithMyFont:你就可以了。
boundingRectWithSize:options:attributes:context:
在Xamarin接受的答案将是(使用sizeWithAttributes和UITextAttributeFont):
UIStringAttributes attributes = new UIStringAttributes
{
Font = UIFont.SystemFontOfSize(17)
};
var size = text.GetSizeUsingAttributes(attributes);
CGSize maximumLabelSize = CGSizeMake(label.frame.size.width, FLT_MAX);
CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
float heightUse = expectedLabelSize.height;
替代解决方案,
CGSize expectedLabelSize;
if ([subTitle respondsToSelector:@selector(sizeWithAttributes:)])
{
expectedLabelSize = [subTitle sizeWithAttributes:@{NSFontAttributeName:subTitleLabel.font}];
}else{
expectedLabelSize = [subTitle sizeWithFont:subTitleLabel.font constrainedToSize:subTitleLabel.frame.size lineBreakMode:NSLineBreakByWordWrapping];
}
推荐文章
- Objective-C中方法混合的危险是什么?
- 如何使用接口生成器创建的nib文件加载UIView
- 如何设置回退按钮文本在Swift
- 如何比较两个nsdate:哪个是最近的?
- 使UINavigationBar透明
- Swift to Objective-C头未在Xcode 6中创建
- setNeedsLayout vs. setNeedsUpdateConstraints和layoutIfNeeded vs. updateConstraintsIfNeeded
- 不区分大小写的比较
- KeyboardEvent。键码弃用。这在实践中意味着什么?
- 编译警告:对于架构i386,没有处理文件的规则
- 从ViewController调用App Delegate方法
- 解释iOS7中automyadjustsscrollviewinsets, extendedlayoutinclesopaquebars, edgesForExtendedLayout之间的区别
- 你能把一个UIGestureRecognizer附加到多个视图吗?
- Pod安装保持在“设置CocoaPods主repo”状态
- 从路径字符串中提取文件名