80

I need to draw a UILabel striked through. Therefore I subclassed UILabel and implemented it as follows:

@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?

I'm also open to any other solutions, if known :)

Best, Erik

jodm
  • 2,607
  • 3
  • 25
  • 40
Erik
  • 11,944
  • 18
  • 87
  • 126

3 Answers3

197

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.

iOS 7 and higher

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

CGFloat strikeWidth = textSize.width;

iOS <7

Prior to iOS7, you had to use the sizeWithFont: method.

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.

starball
  • 20,030
  • 7
  • 43
  • 238
Harry
  • 2,805
  • 1
  • 19
  • 12
  • 5
    sizeWithFont is deprecated since iOS7. Use CGSize textSize = [string sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]}]; instead. – cldrr Oct 11 '13 at 08:47
  • You can also use `label.attributedText.size`. – Jed Fox Oct 11 '15 at 17:12
71

A better solution, here in Swift:
Update:
For 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
Aks
  • 8,181
  • 5
  • 37
  • 38
  • is this ios 7 compatible? – Matej Jan 03 '15 at 13:49
  • This option is significantly faster – Josh Bernfeld May 30 '15 at 20:56
  • Newb question.. Don't you need a width/height to create a label though? At least that's where I am. Trying to find the width of the text that I'm creating a label with. `let sanskritLabel = UILabel(frame: CGRectMake(0, 120, sanskritStringSize.width, sanskritStringSize.height))` – Trip Mar 07 '16 at 17:40
0

This will work. Try it

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