0

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)
}
Giorgio
  • 1,973
  • 4
  • 36
  • 51
장서영
  • 37
  • 4
  • 3
    Use `NSAttributedString` to be able to have different rendering (including colors) in a label (which is "inside" a button), then use `setAttributedTitle(_:for:)`: https://developer.apple.com/documentation/uikit/uibutton/1624012-setattributedtitle – Larme Mar 28 '22 at 13:19

1 Answers1

1

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)
}
Andrew
  • 1,456
  • 15
  • 23