如何使文本标签适合目标c中的矩形

时间:2017-04-19 05:13:37

标签: ios objective-c nsstring uilabel

我有一个包含字符串的标签" Hello"我希望这个标签适合矩形。如何使矩形尺寸与标签尺寸相同?这是我的代码。

int main() {
    // Calling application
    buffer = new unsigned char[width*height*dims];
    ...
    load_offline_image(..., buffer, width, height, ...);
    ...
    delete[] buffer;
}

int load_offline_image(...) {
    Mat offline_image;
    // use imread
    // Copy the buffer over
    memcpy(buffer, offline_image->data, ...);
    // Since we're using the Mat structure, the Mat will be deallocated automatically
}

这是我想要符合我标签的矩形

UiLabel*label = [[UILabel alloc]init];
label.frame = CGRectMake(40,60,50,30);
label.backgroundColor = [UIColor redColor];
label.text = @"Hello";
[label sizeToFit]// it make the size of label fit with text size

1 个答案:

答案 0 :(得分:0)

您也可以使用boundingRectWithSize。它可以用来计算字符串的大小。

NSString *hello = @"Hello";

//or an font you want
UIFont *font =  [UIFont systemFontOfSize:18.0f];

//This is to ensure word wrap is used and the maximum width and height that label size can be calculated is inside screen bounds
CGRect rect = CGRectIntegral([hello boundingRectWithSize:[UIScreen mainScreen].bounds.size options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName : font} context:nil]);

//create Label    
UILabel *tempLabel = [[UILabel alloc] initWithFrame:rect];
[tempLabel setText:hello];
[tempLabel setFont:font];
[tempLabel setNumberOfLines:0];
[tempLabel setLineBreakMode:NSLineBreakByWordWrapping];
[self.view addSubview:tempLabel];