2013-07-18 22 views
1

在我的應用程序的方法,我需要在標籤中顯示下一行文字所以我用下面的代碼顯示下劃線的文字響應於選擇器不支持的實施

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:normalString]; 
    [attributeString addAttribute:NSUnderlineStyleAttributeName 
          value:[NSNumber numberWithInt:1] 
          range:(NSRange){0,[attributeString length]}]; 

wesiteAddressLabel.attributedText = attributeString; 

這種方法和工作正常一些其他實現在iOS的6.1

但是,當我在的iOS 5.1執行及以下,應用進行了由於墜毀的原因,

[attributeString addAttribute:NSUnderlineStyleAttributeName 
          value:[NSNumber numberWithInt:1] 
          range:(NSRange){0,[attributeString length]}]; 

在以前的版本

所以我想用respondsToSelector:方法來檢查實例響應和執行不支持的選擇另一種方法不支持。

我如何使用這種方法?

回答

2

由於從文檔:

attributedText由標籤顯示的樣式文本。

@property(nonatomic,copy)NSAttributedString * attributedText 討論此屬性默認爲零。爲 指定一個新值,該屬性也用 相同的字符串數據替換文本屬性的值,儘管沒有任何格式信息。另外,在 中,分配一個新的值會更新字體, textColor和其他樣式相關屬性中的值,以便它們反映在屬性字符串中從位置0開始的 樣式信息。

Availability在iOS 6.0及更高版本可用。宣佈UILabel.h

你應該檢查的特定UIView元素是能夠向attributedText迴應。在這種情況下:

[wesiteAddressLabel respondsToSelector:@selector(attributedText)]; 

應該是足夠

1

對於previoes版本必須由用在每行文本的高度想起來了下面的文字畫一個UIImageView

或者您可以使用DrawRect方法創建一個標籤類別。

- (void)drawRect:(CGRect)rect 
{ 
    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGContextSetRGBStrokeColor(ctx, 0.0f/255.0f, 0.0f/255.0f, 255.0f/255.0f, 1.0f); // Your underline color 
    CGContextSetLineWidth(ctx, 1.0f); 

    UIFont *font = [UIFont systemFontOfSize:16.0f]; 
    CGSize constraintSize = CGSizeMake(MAXFLOAT, MAXFLOAT); 
    CGSize labelSize; 
    labelSize = [self.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; 

    CGContextMoveToPoint(ctx, 0, self.bounds.size.height - 1); 
    CGContextAddLineToPoint(ctx, labelSize.width + 10, self.bounds.size.height - 1); 

    CGContextStrokePath(ctx); 

    [super drawRect:rect]; 
}