如何在iOS中为uibutton的文本和颜色加下划线

Kas*_*hif 10 iphone sdk uibutton ios

我有一个简单的查询,我需要强调UIButton文本和颜色.我有uibutton的下线文字,但是关于色调,它不起作用.我已经从xib中设置了色调,它没有从那里开始.下面是我的代码.

 NSMutableAttributedString *commentString = [[NSMutableAttributedString alloc] initWithString:@"Testing"];
[commentString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [commentString length])];
[_helpWithLoginLabel setAttributedTitle:commentString forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

Alf*_*sen 8

textColor(NSForegroundColorAttributeName)有一个单独的属性.这是一个例子:

NSArray * keys = [[NSArray alloc] initWithObjects:NSForegroundColorAttributeName, NSUnderlineStyleAttributeName, nil];
NSArray * objects = [[NSArray alloc] initWithObjects:self.descriptionTextView.textColor, [NSNumber numberWithInt:NSUnderlineStyleSingle], nil];
NSDictionary * linkAttributes = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
self.descriptionTextView.linkTextAttributes = linkAttributes;
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助...


Chi*_*buZ 7

在Swift中:

let attributes = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
let attributedText = NSAttributedString(string: button.currentTitle!, attributes: attributes)

button.titleLabel?.attributedText = attributedText
Run Code Online (Sandbox Code Playgroud)


Ced*_*rie 6

使用文字的@dequin响应相同,语法更短:

NSDictionary * linkAttributes = @{NSForegroundColorAttributeName:button.titleLabel.textColor, NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)};
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:button.titleLabel.text attributes:linkAttributes];            
[button.titleLabel setAttributedText:attributedString];
Run Code Online (Sandbox Code Playgroud)


deq*_*uin 5

基于Alfie的回答,我编写了这个解决方案:

NSArray * objects = [[NSArray alloc] initWithObjects:self.aButton.titleLabel.textColor, [NSNumber numberWithInt:NSUnderlineStyleSingle], nil];
NSArray * keys = [[NSArray alloc] initWithObjects:NSForegroundColorAttributeName, NSUnderlineStyleAttributeName, nil];

NSDictionary * linkAttributes = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:self.aButton.titleLabel.text attributes:linkAttributes];

[self.aButton.titleLabel setAttributedText:attributedString];
Run Code Online (Sandbox Code Playgroud)