iOS UILabel动态计算文字高度,显示不全的问题

重构代码时,遇到一个问题。设置label高度为20,动态计算高度为31.1,一直不能双行显示。
后来发现,前辈把addrHeight属性定义为int,系统给四舍五入了。改成CGFloat就好了。

#pragma mark 地址
- (UILabel *)addrLabel {
    if (_addrLabel == nil) {
        _addrLabel = [[UILabel alloc] init];
        _addrLabel.backgroundColor = [UIColor clearColor];
        _addrLabel.lineBreakMode = NSLineBreakByWordWrapping;
        _addrLabel.numberOfLines = 0;
        _addrLabel.font = [UIFont systemFontOfSize:13];
        _addrLabel.textColor = [UIColor colorWithHexString:@"#393939"];
        [self addSubview:_addrLabel];
    }
    return _addrLabel;
}

#pragma mark - 设置Frame
- (void)layoutSubviews {
    [super layoutSubviews];

    CGFloat addrHeight = 20;
    CGFloat addrWidth = kWCScreenSize.width - 2 * kPace - kMargin - kImageWH;
    UIFont *addrFont = [UIFont systemFontOfSize:13];
    NSString *addrStr = _item.receiveaddress;
    CGSize addrSize = [addrStr boundingRectWithSize:CGSizeMake(addrWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:addrFont} context:nil].size;
    if (addrSize.height > 20) {
        addrHeight = addrSize.height;
    }
    self.addrLabel.frame = CGRectMake(kMargin + kImageWH + kPace,
                                      kMargin + self.nameImageView.bottom,
                                      addrWidth,
                                      addrHeight);
    self.size = CGSizeMake(kWCScreenSize.width, self.addrLabel.bottom + kPace);
}

你可能感兴趣的:(iOS UILabel动态计算文字高度,显示不全的问题)