如何在 swift、iOS 中自定义价格按钮文本

How to Customize price button text in swift, iOS

我有 2 个 UIButton,如下图所示。这里我需要为两者自定义完全相同的意思文本,我怎么能这样做。

建议我如何在情节提要中(使用 label/view ..)或以编程方式执行此操作。在标签或按钮文本的情况下,请指导我 NSAttributtedstring 的一些代码,如图所示。

您可以使用 UIViewsUILabels 来设计按钮,并将 tapGestures 添加到 UIViews 以进行用户交互。

您可以在下面使用 func :

extension UILabel {
    func setAttributes(price : String) {
        let font:UIFont? = UIFont.boldSystemFont(ofSize: 22)
        let fontSuper:UIFont? = UIFont.boldSystemFont(ofSize: 15)
        let aDotRange = (price as NSString).range(of: ".")

        let attString:NSMutableAttributedString = NSMutableAttributedString(string: price, attributes: [.font:font!])

        attString.setAttributes([.font:fontSuper!,.baselineOffset:5], range: NSRange(location:0,length:1))

        attString.setAttributes([.font:fontSuper!,.baselineOffset:5],
                                range: NSRange(location:aDotRange.location,length:4))
        attString.setAttributes([.font:font!],
                                range: NSRange(location:1,length:aDotRange.location - 1 ))
        attString.setAttributes([.font:fontSuper!],
                                range: NSRange(location:aDotRange.location + 4,
                                               length: (price.count) - (aDotRange.location + 4) ))
        self.attributedText = attString
    }

}

虚拟代码 :

lblPrice.setAttributes(price: "9.99 / mon")
lblPrice.layer.cornerRadius = 4
lblPrice.layer.borderWidth = 1.0
lblPrice.layer.borderColor = UIColor.blue.cgColor

lblPrice2.setAttributes(price: "9.99 / 6 mo")
lblPrice2.layer.cornerRadius = 4

输出 :