drawInRect:withFont:lineBreakMode:alignment:' is deprecated: warning 和动态获取label的高度

来源:互联网 发布:java 定义泛型返回值 编辑:程序博客网 时间:2024/06/05 12:02
NSString *font = @"Courier-Bold";    #ifdef __IPHONE_7_0        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;        paragraphStyle.alignment = NSTextAlignmentCenter;        [textToDraw drawInRect:renderingRect withAttributes: @{NSFontAttributeName: font,                                                                           NSParagraphStyleAttributeName: paragraphStyle }];        #else        [textToDraw drawInRect:renderingRect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter];        #endif


这里定义NSMutableParagraphStyle类型来添加需要的参数。

- (CGSize)sizeOfTextForCurrentSettings
{
    return [self.badgeText sizeWithAttributes:@{NSFontAttributeName:self.badgeTextFont}];
    //return [self.badgeText sizeWithFont:self.badgeTextFont];
}


 
            CGRect textFrame = rectToDraw;
            CGSize textSize = [self sizeOfTextForCurrentSettings];
            
            textFrame.size.height = textSize.height;
            textFrame.origin.y = rectToDraw.origin.y + ceilf((rectToDraw.size.height - textFrame.size.height) / 2.0f);
            
            
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
            paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
            paragraphStyle.alignment = NSTextAlignmentCenter;
            [self.badgeText drawInRect:textFrame withAttributes:@{NSFontAttributeName:self.badgeTextFont,
                                                                  NSParagraphStyleAttributeName:paragraphStyle}];
            


动态获取label高度,前提是定义的时候高度为0

- (CGFloat)lableFinalHeightWithText:(NSString *)labelText {
    NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:self.font forKey: NSFontAttributeName];
    CGRect endLabelFrame = self.frame;
    endLabelFrame.size = [labelText boundingRectWithSize:CGSizeMake(self.frame.size.width, CGFLOAT_MAX)
                                                         options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin
                                                      attributes:stringAttributes context:nil].size;
    return endLabelFrame.size.height;
}

0 0
原创粉丝点击