如何自定义swift中的价格按钮文本,iOS [关闭]

问题描述 投票:0回答:2

我有2个UIButton,如下图所示。在这里,我需要为两个平均文本定制完全相同,我该怎么做。

建议我如何在storyboard(使用标签/视图..)或以编程方式执行此操作。如图所示,在标签或按钮文字的情况下,引导我使用NSAttributtedstring的一些代码。

enter image description here

ios swift button xcode-storyboard
2个回答
2
投票

你可以在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: "$249.99 / mon")
lblPrice.layer.cornerRadius = 4
lblPrice.layer.borderWidth = 1.0
lblPrice.layer.borderColor = UIColor.blue.cgColor

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

输出:

enter image description here


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.