ios UIButton部分更改标题颜色

czq61nw1  于 2023-08-08  发布在  iOS
关注(0)|答案(1)|浏览(141)


的数据
我想做一个像这张照片一样的纽扣。为了实现它像一个图片,按钮标题的颜色需要部分改变,但我不知道该怎么做。
这是我的代码。

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

字符串

woobm2wo

woobm2wo1#

为此使用NSMutableAttributedString

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)
}

字符串

相关问题