替换ios 7中的弃用sizeWithFont:minFontSIze:actualFontSize

suj*_*uji 6 iphone uifont ios7

在iOS 6中,我使用的是这种方法:

[self.handText sizeWithFont:font 
 minFontSize:10.0f 
 actualFontSize:&maxFontSize 
 forWidth:handWidth/2 
 lineBreakMode:UILineBreakModeClip];
Run Code Online (Sandbox Code Playgroud)

xcode 5说 'sizeWithFont:minFontSIze:actualFontSize:forWidth:lineBreakMode:' is deprecated:first deprecated in iOS 7

现在我实现如下:

[self.handText sizeWithAttributes:@{NSFontAttributeName:font} 
 minFontSize:10.0f 
 actualFontSize:&maxFontSize 
 forWidth:handWidth/2 
 lineBreakMode:NSLineBreakByClipping];
Run Code Online (Sandbox Code Playgroud)

这里xcode抛出另一个警告说: 'Instance method -sizeWithAttributed:minFontSize:forWidth:lineBreakMode:'not found(return type defaults to 'id')

任何人都可以帮我解决这个警告.

7c9*_*fdf 8

请改用此辅助方法:

-(CGSize)frameForText:(NSString*)text sizeWithFont:(UIFont*)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode  {

    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = lineBreakMode;

    NSDictionary * attributes = @{NSFontAttributeName:font,
                                  NSParagraphStyleAttributeName:paragraphStyle
                                  };


    CGRect textRect = [text boundingRectWithSize:size
                                         options:NSStringDrawingUsesLineFragmentOrigin
                                      attributes:attributes
                                         context:nil];

    //Contains both width & height ... Needed: The height
    return textRect.size;
}
Run Code Online (Sandbox Code Playgroud)

如果您需要同时支持iOS 6和iOS 7,请使用如下所示:

#ifdef __IPHONE_7_0

     titleSize = [self frameForText:self.titleLabel.text sizeWithFont:self.titleLabel.font constrainedToSize:CGSizeMake(labelMaxWidth,self.titleLabel.font.lineHeight) lineBreakMode:self.titleLabel.lineBreakMode ];

     subtitleSize = [self frameForText:self.subtitleLabel.text sizeWithFont:self.subtitleLabel.font  constrainedToSize:CGSizeMake(labelMaxWidth,self.subtitleLabel.font.lineHeight) lineBreakMode:self.subtitleLabel.lineBreakMode];

#else


     titleSize = [self.titleLabel.text sizeWithFont:self.titleLabel.font
                                        constrainedToSize:CGSizeMake(labelMaxWidth,self.titleLabel.font.lineHeight)
                                            lineBreakMode:self.titleLabel.lineBreakMode];

     subtitleSize =   [self.subtitleLabel.text sizeWithFont:self.subtitleLabel.font
                                              constrainedToSize:CGSizeMake(labelMaxWidth,self.subtitleLabel.font.lineHeight)
                                                  lineBreakMode:self.subtitleLabel.lineBreakMode];
#endif
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个等价的解决方案,是吗?如果`actualFontSize`不适合约束,那么提问者最初使用的方法将测试各种大小.这个答案中的解决方案似乎没有这样做......? (5认同)