Search code examples
iosswift3uibuttonnsmutableattributedstring

NSAttributedString on UIButton


let strNo = "2222555" // size 18, this should be bold

let remainingStr = "Call to" + "\(strNo)" + "Number" 

Now, in my UIButton, say button, How to set this title "Call to 2222555 number" And i need to change the size according to device, so I have to do it by coding.

Update

I need like following image.

enter image description here

And need to change the size of the title by coding. Above screenshot is from iPhone 7, In iPhone 5 it become bigger and in iPad it become smaller, so i have to set the size of the title according to requirement.

Any help will be appreciable.

Thanks


Solution

  • I found the Answer by struggling few days. And it is quite easy.

    guard
                let font1 = UIFont(name: "HelveticaNeue-Bold", size: 22),
                let font2 = UIFont(name: "HelveticaNeue-Medium", size: 22)  else { return }
    
            let dict1:[String:Any] = [
                //            NSUnderlineStyleAttributeName:NSUnderlineStyle.styleSingle.rawValue,
                NSFontAttributeName:font2,
                NSParagraphStyleAttributeName:style,
                NSForegroundColorAttributeName: UIColor.white
            ]
    
            let dict2:[String:Any] = [
                //            NSUnderlineStyleAttributeName:NSUnderlineStyle.styleNone.rawValue,
                NSFontAttributeName:font1,
                NSParagraphStyleAttributeName:style,
                NSForegroundColorAttributeName: UIColor.white,
                //            NSFontAttributeName: UIFont.boldSystemFont(ofSize: 20)
            ]
    
            let dict3:[String:Any] = [
                //            NSUnderlineStyleAttributeName:NSUnderlineStyle.styleNone.rawValue,
                NSFontAttributeName:font2,
                NSParagraphStyleAttributeName:style,
                NSForegroundColorAttributeName: UIColor.white
            ]
    
            let dict4:[String:Any] = [
                //            NSUnderlineStyleAttributeName:NSUnderlineStyle.styleNone.rawValue,
                NSFontAttributeName:font1,
                NSParagraphStyleAttributeName:style,
                NSForegroundColorAttributeName: UIColor.white
            ]
    
            let attString = NSMutableAttributedString()
            attString.append(NSAttributedString(string: "Call to", attributes: dict1))
            attString.append(NSAttributedString(string: " 2222555 ", attributes: dict2))
            attString.append(NSAttributedString(string: " To Book Your Skip ", attributes: dict3))
            attString.append(NSAttributedString(string: "NOW", attributes: dict4))
    
            btnCall.setAttributedTitle(attString, for: .normal)
    

    And its Working perfectly as expected.