ksm
ksm

Reputation: 21

striking through the text

I need to strike through the text of a multi-line label. Is there a way to do it? Any suggestion would be greatly helpful. Thanks,

Upvotes: 2

Views: 5287

Answers (3)

Mikael Bartlett
Mikael Bartlett

Reputation: 248

Improved @RefuX code to handle location and width of the strikethrough. I will add multiline support soon.

Multiple lines now supported

Gist for UILabelStrikethrough

Upvotes: 2

RefuX
RefuX

Reputation: 511

This will work for a single line label.

@interface UILabelStrikeThrough : UILabel {
}
@end

@implementation UILabelStrikeThrough
- (void)drawRect:(CGRect)rect {
    CGContextRef c = UIGraphicsGetCurrentContext();

    CGFloat black[4] = {0.0f, 0.0f, 0.0f, 1.0f};
    CGContextSetStrokeColor(c, black);
    CGContextSetLineWidth(c, 2);
    CGContextBeginPath(c);
    CGFloat halfWayUp = (self.bounds.size.height - self.bounds.origin.y) / 2.0;
    CGContextMoveToPoint(c, self.bounds.origin.x, halfWayUp );
    CGContextAddLineToPoint(c, self.bounds.origin.x + self.bounds.size.width, halfWayUp);
    CGContextStrokePath(c);

    [super drawRect:rect];
}

@end

Upvotes: 2

Vladimir
Vladimir

Reputation: 7801

if you want do it with UILabel for iPhone you can't :(

so there are 3 ways:

  1. (simplest) use UIWebView:

    // set html header with styles, you can certainly use some other attributes       
    NSString * htmlWrap =  @"<html><head><style>body{text-align:left; background-color:transparent; color:black; font-weight:bold; text-decoration:line-through; font-size:%dpt}`</style></head>`<body>%@</body`></html>";
    NSStrring * myText = @"My sample strikethrough text";
    webView.backgroundColor =  [UIColor clearColor];
    [webView setOpaque:NO];
    NSString * htmlText = [NSString stringWithFormat:htmlWrap, 12, myText];
    [webView loadHTMLString:htmlText baseURL:nil];
    
  2. use unicode combining diacritic (this works with any objects labels, textfields etc.)

    "long stroke overlay" (U+0336) or
    "combining low line" (U+0332) before
    each charecter in your string. Use

     -(void)getCharacters:(unichar *)buffer range:(NSRange)aRange
    

    to create unichar array from string (allocate double size of string length), then rearrange array and add U+0336 or U+0332 before each character, then convert unichar array back to NSString with

     -(id)initWithCharacters:(const unichar *)characters length:(NSUInteger)length
    

    but in most cases this looks bad

  3. Draw it manualy on context.

Upvotes: 3

Related Questions