我有一个简单的查询,我需要为UIButton文本和颜色加下划线。我有uibutton的下线文字,但是关于色调,它不起作用。我已经从xib设置了色调,它没有从那里开始.Below是我的代码。
NSMutableAttributedString *commentString = [[NSMutableAttributedString alloc] initWithString:@"Testing"];
[commentString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [commentString length])];
[_helpWithLoginLabel setAttributedTitle:commentString forState:UIControlStateNormal];
答案 0 :(得分: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;
希望这会有所帮助......
答案 1 :(得分:7)
在斯威夫特:
let attributes = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
let attributedText = NSAttributedString(string: button.currentTitle!, attributes: attributes)
button.titleLabel?.attributedText = attributedText
答案 2 :(得分:6)
与使用文字的@dequin相同的响应会缩短语法:
NSDictionary * linkAttributes = @{NSForegroundColorAttributeName:button.titleLabel.textColor, NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)};
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:button.titleLabel.text attributes:linkAttributes];
[button.titleLabel setAttributedText:attributedString];
答案 3 :(得分: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];
答案 4 :(得分:1)
试试这个: -
extension UIButton {
func UnderlineTextButton(title: String?, forState state: UIControlState)
{
self.setTitle(title, for: .normal)
self.setAttributedTitle(self.attributedString(), for: .normal)
}
private func attributedString() -> NSAttributedString? {
let attributes = [
NSFontAttributeName : UIFont.systemFont(ofSize: 12.0),
NSForegroundColorAttributeName : UIColor.black,
NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue
] as [String : Any]
let attributedString = NSAttributedString(string: self.currentTitle!, attributes: attributes)
return attributedString
}
}
用途: -
button.UnderlineTextButton(title: "Click Here", forState:
UIControlState.normal)