0

I have a UILabel I want to make some part of it as underline. I am using below code for that. But it underline the whole label not the some part of label. Please tell me how can I make some part of label as Underline.

let attributedString = NSMutableAttributedString(string: "UserAgreement".localized)
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 0, length: 10))

labelTc.attributedText = attributedString

I don't want to do with the storyboard

rmaddy
  • 314,917
  • 42
  • 532
  • 579
TechChain
  • 8,404
  • 29
  • 103
  • 228
  • Follow this link: https://stackoverflow.com/questions/28268060/adding-underline-attribute-to-partial-text-uilabel-in-storyboard – BuLB JoBs Nov 15 '17 at 13:52
  • You must read my question before suggestion. First i want to do it progrmatically. Second i have tried which does not solve my problem – TechChain Nov 15 '17 at 13:54

1 Answers1

5

Try this

Swift 4

    let wholeStr = "Don't have an account? Register"
    //let rangeToUnderLine = (wholeStr as NSString).range(of: "Register")
    let rangeToUnderLine = NSRange(location: 0, length: 10))
    let underLineTxt = NSMutableAttributedString(string: wholeStr, attributes: [NSAttributedStringKey.font:UIFont.systemFont(ofSize: 20),NSAttributedStringKey.foregroundColor: UIColor.white.withAlphaComponent(0.8)])
    underLineTxt.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: rangeToUnderLine)
    labelTc.attributedText = underLineTxt

Swift 3.2

    let wholeStr = "Don't have an account? Register"
    //let rangeToUnderLine = (wholeStr as NSString).range(of: "Register")
    let rangeToUnderLine = NSRange(location: 0, length: 10))
    let underLineTxt = NSMutableAttributedString(string: wholeStr, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 20),NSForegroundColorAttributeName: UIColor.white])
    underLineTxt.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: rangeToUnderLine)
    labelTc.attributedText = underLineTxt

enter image description here

RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70