gpt4 book ai didi

swift - 如何在 Swift 中更改 UIButton 的字母间距?

转载 作者:IT王子 更新时间:2023-10-29 05:45:45 28 4
gpt4 key购买 nike

我找到了如何将字母间距设置为 UILabel ( here ),但此方法不适用于 UIButton。有谁知道怎么做吗?

这是我正在使用的代码

    let buttonString = agreementButton.attributedTitleForState(.Normal) as! NSMutableAttributedString
buttonString.addAttribute(NSKernAttributeName, value: 1.0, range: NSMakeRange(0, buttonString.length))
agreementButton.setAttributedTitle(buttonString, forState: .Normal)

它抛出一个错误:'NSConcreteAttributedString' (0x19e508660) to 'NSMutableAttributedString' (0x19e506a40)。

最佳答案

swift 3.0

extension UIButton{
func addTextSpacing(spacing: CGFloat){
let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
attributedString.addAttribute(NSKernAttributeName, value: spacing, range: NSRange(location: 0, length: (self.titleLabel?.text!.characters.count)!))
self.setAttributedTitle(attributedString, for: .normal)
}
}
btnRegister.addTextSpacing(spacing: 4.5)

extension UILabel{
func addTextSpacing(spacing: CGFloat){
let attributedString = NSMutableAttributedString(string: self.text!)
attributedString.addAttribute(NSKernAttributeName, value: spacing, range: NSRange(location: 0, length: self.text!.characters.count))
self.attributedText = attributedString
}
}
lblOne.addTextSpacing(spacing: 4.5)

extension UITextField{
func addPlaceholderSpacing(spacing: CGFloat){
let attributedString = NSMutableAttributedString(string: self.placeholder!)
attributedString.addAttribute(NSKernAttributeName, value: spacing, range: NSRange(location: 0, length: self.placeholder!.characters.count))
self.attributedPlaceholder = attributedString
}
}
txtUserName.addPlaceholderSpacing(spacing: 4.5)

extension UINavigationItem{
func addSpacing(spacing: CGFloat){
let attributedString = NSMutableAttributedString(string: self.title!)
attributedString.addAttribute(NSKernAttributeName, value: spacing, range: NSRange(location: 0, length: self.title!.characters.count))
let label = UILabel()
label.textColor = UIColor.black
label.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightBold)
label.attributedText = attributedString
label.sizeToFit()
self.titleView = label
}
}
navigationItem.addSpacing(spacing: 2.5)

关于swift - 如何在 Swift 中更改 UIButton 的字母间距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34048850/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com