2013-10-30 27 views
0

我在視圖中插入了兩個標籤。當我點擊其中一個標籤時,我想運行一些代碼隱藏(更改子視圖),並且標籤中的文本應加下劃線。如何實現帶有帶下劃線文本的標籤按鈕

這應該如何在Cocoa中實現?

+0

你可以嘗試抓住了按鈕的'titleLabel'屬性,然後設置標籤的'attributedText'。 –

+0

何時使用屬性文本? – dhrm

+0

其實,不知道爲什麼我在這個切線上去...看到我的答案在下面。 –

回答

2

子類的NSTextField並執行其鼠標按下:事件作爲

@interface ClickableLabel : NSTextField 

@end 


@implementation ClickableLabel 

- (void)mouseDown:(NSEvent *)theEvent 
{ 
    [super mouseDown:theEvent]; 

    NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString: [self stringValue]]; 
    NSRange range = NSMakeRange(0, [attrString length]); 

    [attrString beginEditing]; 

    // make the text appear with an underline 
    [attrString addAttribute: NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSSingleUnderlineStyle] range:range]; 

    [attrString endEditing]; 

    [self setAttributedStringValue:attrString]; 

    [attrString release]; 
} 

@end 

設置此ClickableLabel作爲標籤的類

0

要在標籤中加下劃線文字,請設置其attributedText屬性。所以,你可以這樣做:

- (void)underlineRange:(NSRange)range forLabel:(UILabel *)label 
{ 
    NSMutableAttributedString *aText = [[NSMutableAttributedString alloc] initWithString:label.text]; 
    [aText addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:range]; 
    label.attributedText = aText; 
} 

順便說一句,我寫上面的評論,我想你想強調一個UIButton文本。有一種更直接的方法,使用UIButtonsetAttributedTitle:forState方法。