0
import Foundation
import UIKit


extension NSMutableAttributedString {

    @discardableResult
    public func setAsLink(textToFind: NSMutableAttributedString, linkURL: String) -> Bool {

        let foundRange = self.mutableString.range(of: textToFind)
        if foundRange.location != NSNotFound {
            self.addAttribute(NSLinkAttributeName, value: linkURL, range: foundRange)
            return true
        }
        return false
    }
}



@IBDesignable
class SignUpLabel: UILabel {

    override func layoutSubviews() {
        super.layoutSubviews()

        let normalText = "Don't have an account yet? "
        let normalString = NSMutableAttributedString(string: normalText)

        let boldText  = "Sign up now!"
        let attrs = [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14)]
        let attributedString = NSMutableAttributedString(string: boldText, attributes: attrs)

        normalString.append(attributedString)

        self.attributedText = normalString

        normalString.setAsLink(textToFind: attributedString, linkURL: "http://www.someaddress.com")

    }

}

let foundRange = self.mutableString.range(of: textToFind) requires String but I have declared it as a NSMutableAttributedString so I would be able to add weight to specific part of the label.

I can't figure it out. Can somebody please help me with the fix? I would really appreciate it.

Benjamin Lowry
  • 3,730
  • 1
  • 23
  • 27

1 Answers1

0

NSMutableAttributedString has a property called string. To access it, and allow for searching, use yourMutableAttributedString.string as the argument.

Acoop
  • 2,586
  • 2
  • 23
  • 39