objective-c UILabel 中文本的像素宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1340667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pixel Width of the text in a UILabel
提问by Erik
I need to draw a UILabel striked through. Therefore I subclassed UILabel and implemented it as follows:
我需要绘制一个被删除的 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
What happens is that the the UILabel is striked through with a line being as long as the whole label, but the text can be shorter. Is there a way to determine the length of the text in pixels, such that the line can appropriately be drawn?
发生的情况是 UILabel 被一条与整个标签一样长的线划掉,但文本可以更短。有没有办法以像素为单位确定文本的长度,以便可以适当地绘制线条?
I'm also open to any other solutions, if known :)
如果知道,我也愿意接受任何其他解决方案:)
Best, Erik
最好的,埃里克
回答by Harry
NSString has a sizeWithAttributes:method that can be used for this. It returns a CGSize structure, so you could do something similar to the following to find the width of the text inside your label.
NSString 有一个sizeWithAttributes:方法可以用于此。它返回一个 CGSize 结构,因此您可以执行与以下类似的操作来查找标签内文本的宽度。
iOS 7 and higher
iOS 7 及更高版本
CGSize textSize = [[label text] sizeWithAttributes:@{NSFontAttributeName:[label font]}];
CGFloat strikeWidth = textSize.width;
iOS <7
iOS <7
Prior to iOS7, you had to use the sizeWithFont:method.
在 iOS7 之前,您必须使用sizeWithFont:方法。
CGSize textSize = [[label text] sizeWithFont:[label font]];
CGFloat strikeWidth = textSize.width;
UILabel has a font property that you can use to dynamically get the font details for your label as i'm doing above.
UILabel 有一个 font 属性,您可以使用它来动态获取标签的字体详细信息,就像我在上面所做的那样。
Hope this helps :)
希望这可以帮助 :)
回答by Aks
A better solution, here in Swift:
Update:
For Swift 3/4:
一个更好的解决方案,在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)")
Old Answer:
旧答案:
yourLabel?.text = "Test label text" // sample label text
let labelTextWidth = yourLabel?.intrinsicContentSize().width
let labelTextHeight = yourLabel?.intrinsicContentSize().height

