UILabel中文本的像素宽度

时间:2009-08-27 12:10:49

标签: iphone objective-c uilabel

我需要绘制一个UILabel。因此,我将UILabel子类化并按如下方式实现:

@implementation UIStrikedLabel

- (void)drawTextInRect:(CGRect)rect{
    [super drawTextInRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextFillRect(context,CGRectMake(0,rect.size.height/2,rect.size.width,1));
}
@end

UILabel的线条与整个标签一样长,但文字可以更短。 有没有办法确定文本的长度(以像素为单位),以便可以适当地绘制线条?

我也对任何其他解决方案持开放态度,如果已知:)

最佳, 埃里克

4 个答案:

答案 0 :(得分:194)

NSString有一个sizeWithAttributes:方法可用于此目的。它返回一个CGSize结构,因此您可以执行与以下内容类似的操作来查找标签内文本的宽度。

iOS 7及更高版本

CGSize textSize = [[label text] sizeWithAttributes:@{NSFontAttributeName:[label font]}];

CGFloat strikeWidth = textSize.width;

iOS< 7

在iOS7之前,您必须使用sizeWithFont:方法。

CGSize textSize = [[label text] sizeWithFont:[label font]];

CGFloat strikeWidth = textSize.width;

UILabel有一个字体属性,您可以使用它来动态获取标签的字体详细信息,如上所述。

希望这会有所帮助:)

答案 1 :(得分:64)

更好的解决方案,点击 Swift
更新
对于Swift 3/4

@IBOutlet weak var testLabel: UILabel!
// in any function
testLabel.text = "New Label Text"
let width = testLabel.intrinsicContentSize.width
let height = testLabel.intrinsicContentSize.height
print("width:\(width), height: \(height)")

旧答案:

yourLabel?.text = "Test label text" // sample label text
let labelTextWidth = yourLabel?.intrinsicContentSize().width
let labelTextHeight = yourLabel?.intrinsicContentSize().height

答案 2 :(得分:1)

希望此示例可以为您提供帮助(iOS> 7)

NSString *text = @"    // Do any additional setup after loading the view, typically from a nib.";
CGRect rect = CGRectZero;
NSDictionary *attrDict = @{NSFontAttributeName : [UIFont systemFontOfSize:17]};

rect = [text boundingRectWithSize:CGSizeMake(100,9999)
                          options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                       attributes:attrDict
                          context:Nil];

UILabel *lbl = [[UILabel alloc] init];
lbl.text = text;
rect.origin = CGPointMake(50, 200);
lbl.frame = rect;
lbl.lineBreakMode = NSLineBreakByWordWrapping;
lbl.numberOfLines = 0;
[self.view addSubview:lbl];

答案 3 :(得分:0)

这将起作用。试试吧

NSDictionary *attrDict = @{NSFontAttributeName : [GenericUtility getOpenSansRegularFontSize:12]};
CGSize stringBoundingBox = [selectedReservationModel.DateLabel sizeWithAttributes: attrDict];
lblDeliveryDateWidth = stringBoundingBox.width;