Search code examples
iosswiftbuttonxcode-storyboard

How to Customize price button text in swift, iOS


I have 2 UIButton as shown in below image. Here I need to customize exactly the same for both, mean texts, how could I do this.

Suggest how could I do this either in storyboard (using label/view ..) or programmatically. Guide me with some piece of code for NSAttributtedstring in case of label or button text as shown in image.

enter image description here


Solution

  • You can use this below 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
        }
    
    }
    

    Dummy code :

    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
    

    Output :

    enter image description here