[英]UIButton: draw a line below text with x pts spacing?
我需要在UIButton
中的文本下方画一条线,并且看到一些项目在UIButton
带有下划线,其视图具有适合按钮宽度的视图,并通过高度约束固定在其底部,但这实际上并不是我所需要的,对于我的情况,我想我可能需要知道文本的位置/大小,以便将线精确地放置在文本下方?
谢谢!
编辑:
对不起,我需要注意的是,我不需要下划线,我需要的是按钮标题标签下方的选择指示器,说我必须按下按钮:
标题1标题 2
当前高亮显示在第一个按钮标题下方,当我选择第二个按钮时,我希望它移至第二个按钮标题下方。
您可以使用任意间距将边框添加到UIButton的titleLabel属性。
目标C
CGFloat space = 10;
[_button setNeedsLayout];
[_button layoutIfNeeded];
CALayer *border = [[CALayer alloc] init];
border.backgroundColor = [UIColor redColor].CGColor;
border.frame = CGRectMake(0, _button.titleLabel.frame.size.height + space, _button.titleLabel.frame.size.width, 1);
[_button.titleLabel.layer addSublayer:border];
迅捷3
let space:CGFloat = 10
button.setNeedsLayout()
button.layoutIfNeeded()
let border = CALayer()
border.backgroundColor = UIColor.red.cgColor
border.frame = CGRect(x: 0, y: (button.titleLabel?.frame.size.height)! + space, width: (button.titleLabel?.frame.size.width)!, height: 1)
button.titleLabel?.layer.addSublayer(border)
您正在寻找的是NSAttributedString
。 属性字符串可用于添加下划线或使文本变为粗体或任何其他属性。 要在UIButton
添加下划线:
NSString *string = @"yo";
NSAttributedString *textString = [[NSAttributedString alloc] initWithString:string attributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)}];
[mainButton setAttributedTitle:textString forState:UIControlStateNormal];
最简单的解决方案是将按钮标题更改为属性字符串,然后设置下划线属性:
NSDictionary * underlineAttributes = @{NSForegroundColorAttributeName:button.titleLabel.textColor, NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)};
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:button.titleLabel.text attributes:linkAttributes];
[button.titleLabel setAttributedText:attributedString];
请注意,您还需要设置文本颜色属性,因为默认情况下,属性文本将不使用按钮的titleColor。
但是,如果您希望对线条及其属性(位置,长度,高度等)进行更多控制,则它将变得更加复杂,并且可能需要将UIButton子类化并覆盖drawRect
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.