首页 > 解决方案 > 具有系统字体、粗体和字距调整的 UIButton 子类

问题描述

您必须使用属性文本来进行字距调整。但。另一方面,您无法在 IB 属性文本菜单中获取系统字体。

我如何制作(在代码中)UIButton具有

理想情况下,它将从 IB 中的纯文本标题中收集按钮的文本。但是,如果必须在代码中设置文本,那很好。

class NiftyButton: UIButton { 
    ????
}

通常我像这样初始化 UIButton .. 但我什至不知道这是否是最好的地方?(你不能在 layoutSubviews 中这样做,因为它当然会循环。)

class InitializeyButton: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        common()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        common()
    }

    func common() {
        ...
    }
}

如何在代码中实现...

标签: iosswiftuibuttonnsattributedstring

解决方案


这是您可以用来获得所需结果的类:

class InitializeyButton: UIButton {

   @IBInspectable var spacing:CGFloat = 0 {
      didSet {
        updateTitleOfLabel()
      }
   }

   override func setTitle(_ title: String?, for state: UIControl.State) {

        let color = super.titleColor(for: state) ?? UIColor.black
        let attributedTitle = NSAttributedString(
            string: title ?? "",
            attributes: [NSAttributedString.Key.kern: spacing,
                         NSAttributedString.Key.foregroundColor: color,
                         NSAttributedString.Key.font: UIFont.systemFont(ofSize: self.titleLabel?.font.pointSize ?? 11, weight: .bold)   ])
        super.setAttributedTitle(attributedTitle, for: state)
   }

  private func updateTitleOfLabel() {
    let states:[UIControl.State] = [.normal, .highlighted, .selected, .disabled]
      for state in states {
        let currentText = super.title(for: state)
        self.setTitle(currentText, for: state)
      }
   }
}

推荐阅读