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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2645393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:08:44  来源:igfitidea点击:

How to display Underlined Text in a Button on iOS?

ioshyperlinkuibuttonuilabelmfmailcomposeviewcontroller

提问by Warrior

I want to display the mail ID in my view such that clicking the mail ID should open the mail composer view.

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

I want to display the button text as underlined to show it is a hyperlink and for the button click event to call the mail composer view. At present, I am not able to show the button text underlined.

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

I thought of placing a label above the button and adjusting the label property to get the underlined text but that did not work.

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

Is there a different way to get the appearance and behavior I want?

有没有不同的方法来获得我想要的外观和行为?

采纳答案by TechZen

Another alternative is to set an image for the button. Create an image that displays the appropriate text and the button will display that instead of text.

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

I agree with Zack that underlining text is redundant and violates the interface grammar. You underline text for links in the first place to indicate that they have behavior like buttons. If the text is already in a button, there is no need to underline it to indicate it behaves like a button because the user already expects an action in response to clicking it.

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

回答by Robert Chen

Adding a screenshot for @Haider's answer.

为@Haider 的回答添加屏幕截图。

Note:Only the text you highlight gets underlined, so you can underline just a specific range if you want.

注意:只有突出显示的文本会带有下划线,因此您可以根据需要仅在特定范围内添加下划线。

enter image description here

在此处输入图片说明

I ended up underlining it in code anyway, just because I couldn't get Boldto work in conjunction with Underline for some reason. Could have been because of the font I was using, who knows.

无论如何,我最终还是在代码中给它加了下划线,只是因为出于某种原因我无法让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)
    }
}

回答by Haider

To do it in interface builder

在界面生成器中进行

  1. Click on button/label
  2. In Attributes inspector, change Title/Textto Attributed from plain
  3. Select the text which you want to show.
  4. Right click on it Goto Font->Underline
  1. 单击按钮/标签
  2. 在属性检查器中,将标题/文本从普通更改为属性
  3. 选择要显示的文本。
  4. 右键单击它转到字体->下划线

回答by Kirit Vaghela

Swift 3.2

斯威夫特 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
}

Objective C

目标 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;
}

回答by Erwan

Since iOS 6.0 you can use NSAttributedStringwith UIButton.

由于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];

回答by Zack

To do what you want, you would need to use CGContextStrokePath() to draw the underline on the UILabel's CGLayer.

要执行您想要的操作,您需要使用 CGContextStrokePath() 在 UILabel 的 CGLayer 上绘制下划线。

That being said, I would challenge you to reconsider your design choice. Making the button text appear to be a hyperlink would make sense a Windows desktop application (e.g. using a LinkLabel). However, the iPhone OS has a different set of user interface conventions owing to its smaller screen and the need for larger targets to accommodate touch input.

话虽如此,我会挑战您重新考虑您的设计选择。使按钮文本看起来像一个超链接对于 Windows 桌面应用程序是有意义的(例如使用LinkLabel)。然而,iPhone OS 有一套不同的用户界面约定,因为它的屏幕更小,并且需要更大的目标来适应触摸输入。

The "Cocoa Touch" approach to this problem would be to display a list of mail id's using a UITableView. Provide each row with an appropriate accessory button. For example, you could use either a UITableViewCellAccessoryDetailDisclosureButton, or an UIButtonwith buttonTypeof UIButtonTypeContactAdd). The accessory button event handler would then bring up the mail composer.

解决此问题的“Cocoa Touch”方法是使用 UITableView 显示邮件 ID 列表。为每一行提供一个合适的附件按钮。例如,你可以使用一个 UITableViewCellAccessoryDetailDisclosureButton,或UIButtonbuttonTypeUIButtonTypeContactAdd)。然后,附件按钮事件处理程序将调出邮件编辑器。

Good luck, and happy coding!

祝你好运,编码愉快!

回答by trillions

simple, using a webview and plug in a block of html to display any text that iphone cannot do but html can.

很简单,使用 webview 并插入一个 html 块来显示 iphone 不能做但 html 可以的任何文本。

回答by Stephen Chen

Thanks to @Robert Chen's answer , Update to swift 4.1

感谢@Robert Chen 的回答,更新到 swift 4.1

let btn = UIButton(type: .system)
btn.frame = CGRect(x: 100, y: 100, width: 100, height: 100)

let attrs = NSAttributedString(string: "? More",
               attributes:
[NSAttributedStringKey.foregroundColor: UIColor(red:0.20, green:1.00, blue:1.00, alpha:1.0),
 NSAttributedStringKey.font: UIFont.systemFont(ofSize: 19.0),
 NSAttributedStringKey.underlineColor: UIColor(red:0.20, green:1.00, blue:1.00, alpha:1.0),
 NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue])

btn.setAttributedTitle(attrs, for: .normal)

enter image description here

在此处输入图片说明

回答by user7865437

So what if you want to provide a link to a website within a block of text? The user would need some visual indication the text is a link and will take them somewhere.

那么,如果您想在一段文本中提供指向网站的链接怎么办?用户需要一些视觉指示文本是一个链接并将它们带到某个地方。

The blue underlined hyperlinked look is the expected norm but understand this is the PC way. So what is the iPhone way?

蓝色带下划线的超链接外观是预期的规范,但请理解这是 PC 方式。那么iPhone的方式是什么?

I have in the past used a custom button with no background etc and blue text, although not underlined it does allow tappable text.

我过去使用过一个没有背景等和蓝色文本的自定义按钮,虽然没有下划线它确实允许点击文本。

Would be interested to know what others do....

有兴趣知道其他人是做什么的......

回答by Agnieszka Duch

Or you can create an extension to UIButton (Swift 5):

或者您可以创建 UIButton (Swift 5) 的扩展:

extension UIButton {
    func underline() {
        if let textUnwrapped = self.titleLabel?.text {
            let underlineAttribute = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue]
            let underlineAttributedString = NSAttributedString(string: textUnwrapped, attributes: underlineAttribute)
            self.setAttributedTitle(underlineAttributedString, for: .normal)
        }
    }
}