How to display Underlined Text in a Button on iOS?

后端 未结 10 1625
日久生厌
日久生厌 2020-12-16 15:20

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

I want to display the button text as underlined to show i

相关标签:
10条回答
  • 2020-12-16 15:31

    Since iOS 6.0 you can use NSAttributedString with UIButton.

    //create an underlined attributed string
    NSAttributedString *titleString = [[NSAttributedString alloc] initWithString:@"Title" attributes:@{NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle | NSUnderlinePatternSolid)}];
    
    //use the setAttributedTitle method
    [yourButton setAttributedTitle:titleString forState:UIControlStateNormal];
    
    0 讨论(0)
  • 2020-12-16 15:34

    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?

    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....

    0 讨论(0)
  • 2020-12-16 15:38

    Thanks to @Robert Chen's answer , Update to 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)
    

    0 讨论(0)
  • 2020-12-16 15:39

    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.

    0 讨论(0)
提交回复
热议问题