iPhone:如何在按钮中显示带下划线的文本?

War*_*ior 13 iphone hyperlink uibutton uilabel mfmailcomposeviewcontroller

我想在我的视图中显示邮件ID,以便单击邮件ID应该打开邮件编辑器视图.

我想以下划线显示按钮文本,以显示它是一个超链接,并为按钮单击事件调用邮件编辑器视图.目前,我无法显示下划线的按​​钮文字.

我想在按钮上方放置一个标签并调整label属性以获得带下划线的文本,但这不起作用.

是否有不同的方式来获得我想要的外观和行为?

Rob*_*hen 39

为@ Haider的答案添加截图.

注意:只有您突出显示的文本带有下划线,因此您可以根据需要为特定范围加下划线.

在此输入图像描述

最后我最后在代码中强调了它,因为我无法让Bold因为某些原因与Underline一起工作.可能是因为我使用的字体,谁知道.

@IBOutlet weak var underlineButton: UIButton! {
    didSet {
        let attrs = [
            NSFontAttributeName : UIFont(name: "MyCustomFont-Bold", size: 19.0)!,
            NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue,
            NSForegroundColorAttributeName : UIColor.orangeColor()
        ]
        let attrString = NSMutableAttributedString(string: "Button text", attributes:attrs)
        underlineButton.setAttributedTitle(attrString, forState: .Normal)
    }
}
Run Code Online (Sandbox Code Playgroud)


Hai*_*der 8

在界面构建器中执行此操作

  1. 单击按钮/标签
  2. 在"属性"检查器中,将" 标题/文本"更改为"从纯文本归属"
  3. 选择要显示的文本.
  4. 右键单击它转到字体 - >下划线


Kir*_*ela 6

Swift 3.2

if let title = button.titleLabel?.text, title != "" {

    let attributeString = NSMutableAttributedString(string: title)

    attributeString.addAttribute(NSAttributedStringKey.underlineStyle, value: 1, range: NSMakeRange(0, title.count))

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

目标C.

NSString *tem = self.myButton.titleLabel.text;

if (tem != nil && ![tem isEqualToString:@""]) {
    NSMutableAttributedString *temString=[[NSMutableAttributedString alloc]initWithString:tem];
    [temString addAttribute:NSUnderlineStyleAttributeName
                      value:[NSNumber numberWithInt:1]
                      range:(NSRange){0,[temString length]}];

    self.myButton.titleLabel.attributedText = temString;
}
Run Code Online (Sandbox Code Playgroud)


Erw*_*wan 5

由于iOS的6.0你可以用NSAttributedStringUIButton

//create an underlined attributed string
NSAttributedString *titleString = [[NSAttributedString alloc] initWithString:@"Title" attributes:@{NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle | NSUnderlinePatternSolid)}];

//use the setAttributedTitle method
[yourButton setAttributedTitle:titleString forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)


Tec*_*Zen 2

另一种选择是为按钮设置图像。创建一个显示适当文本的图像,按钮将显示该图像而不是文本。

我同意扎克的观点,即下划线文本是多余的并且违反了界面语法。首先为链接的文本添加下划线,以表明它们具有类似于按钮的行为。如果文本已经在按钮中,则无需在其下划线以指示其行为类似于按钮,因为用户已经期望响应单击它的操作。