iosswiftuibuttonnsattributedstringsetattribute

UIButton Change Title Color Partially


enter image description here

I want to make button like this picture. In order to implement it like a picture, the color of the button title needs to be partially changed, but I don't know what to do.

Here is my code.

 private let signUpButton = UIButton().then {
    $0.setTitleColor(.black, for: .normal)
    $0.titleLabel?.font = .boldSystemFont(ofSize: 12)
}

Solution

  • Use NSMutableAttributedString for this purpose

    private let signUpButton = UIButton().then {
      // Creating gray text part
      let grayButtonText = NSAttributedString(string: "FirstPart", attributes: [.font: UIFont.systemFont(ofSize: 12), .foregroundColor: UIColor.gray ])
      // Creating black text part
      let blackButtonText = NSAttributedString(string: "SecondPart", attributes: [.font: UIFont.systemFont(ofSize: 12), .foregroundColor: UIColor.black ])
    
      // Merging two parts together
      let buttonTitle = NSMutableAttributedString(attributedString: grayButtonText)
      buttonTitle.append(blackButtonText)
      
      // Set it as a title for ".normal" state
      $0.setAttributedTitle(buttonTitle, for: .normal)
    }