2014-04-14 10 views
0

我創建了一個按鈕,需要爲selectedElement中的文本加下劃線。如何創建一個強調文本的按鈕?

到目前爲止我有這個代碼,但它只適用於如果你HIGHLIGHT文本,然後按下劃線。我需要它將它強調爲下劃線,而不必突出顯示文本。如果您再次按下下劃線按鈕,如何解除下劃線的任何幫助也是受歡迎的。非常感謝您的參與!我是新手):

-(void)underlineTextButton{ 
    UITextView selectedText = (UITextView) selectedElement; 
    NSRange range = selectedText.selectedRange; 
    NSTextStorage *textStorage = selectedText.textStorage; 
    [textStorage addAttribute: NSUnderlineStyleAttributeName 
    value:[NSNumber numberWithInt:NSUnderlineStyleSingle] 
    range:range]; 
} 
+2

請檢查[NSAttributedString](https://developer.apple.com/library/mac/documentation/cocoa/reference/基礎/班/ NSAttributedString_Class /參考/的reference.html)。 – cojoj

+0

仍然沒有運氣): – Camerz007

回答

0

你可以使用:

-(void) viewDidLoad 
{ 
    //If it gonna be the static text 
    _textView.attributedText = [[NSAttributedText alloc] initWithString:@"Your <u>underlined</u> text goes here.."]; 

    // If need to by text using regex 
    NSRange r; 
    NSString *s = _textView.text; 
    while ((r = [s rangeOfString:@"patternText" options:NSRegularExpressionSearch]).location != NSNotFound) 
    s = [s stringByReplacingCharactersInRange:r withString:[NSString stringWithFormat:@"<u>%@</u>", patternText]]; 
    _textView.attributtedText = [[NSAttributedText alloc] initWithString:s]; 

} 
相關問題