Programmatically set image and text on UIButton

后端 未结 6 1767
孤街浪徒
孤街浪徒 2020-12-28 13:46

I need to create button programatically with an image for normal and highlighted state as well text. I cannot build it using Interface Builder, because I need to create butt

6条回答
  •  误落风尘
    2020-12-28 13:56

    Swift 4

    • You can set the image and text together as a attribute text and you can do this by implementing below code:
    • here i have customised function in which you can pass the title string and button image it will returned you an attributed text and you can set on UIButton/UILabel title as a attributed title/text.

    - if you want to display an image prefix with title

    func AttributedTextwithImagePrefix(AttributeImage : UIImage , AttributedText : String , buttonBound : UIButton) -> NSMutableAttributedString
    {
        let fullString = NSMutableAttributedString(string: "   ")
        let image1Attachment = NSTextAttachment()
        image1Attachment.bounds = CGRect(x: 0, y: ((buttonBound.titleLabel?.font.capHeight)! - AttributeImage.size.height).rounded() / 2, width: AttributeImage.size.width, height: AttributeImage.size.height)
        image1Attachment.image = AttributeImage
        let image1String = NSAttributedString(attachment: image1Attachment)
        fullString.append(image1String)
        fullString.append(NSAttributedString(string: "  " + AttributedText))
        return fullString
    }
    

    this is how you can use this :

    self.btnprefix.setAttributedTitle(AttributedTextwithImagePrefix(AttributeImage: #imageLiteral(resourceName: "avtar"), AttributedText: " prefix avtar", buttonBound: self.prefix), for: .normal)
    

    - if you want to display an image suffix with title

    func AttributedTextwithImageSuffix(AttributeImage : UIImage , AttributedText : String , buttonBound : UIButton) -> NSMutableAttributedString
    {
        let fullString = NSMutableAttributedString(string: AttributedText + "  ")
        let image1Attachment = NSTextAttachment()
        image1Attachment.bounds = CGRect(x: 0, y: ((buttonBound.titleLabel?.font.capHeight)! - AttributeImage.size.height).rounded() / 2, width: AttributeImage.size.width, height: AttributeImage.size.height)
        image1Attachment.image = AttributeImage
        let image1String = NSAttributedString(attachment: image1Attachment)
        fullString.append(image1String)
        fullString.append(NSAttributedString(string: ""))
        return fullString
    }
    

    this is how you can use this :

    self.btnsuffix.setAttributedTitle(AttributedTextwithImageSuffix(AttributeImage: #imageLiteral(resourceName: "avtar"), AttributedText: " suffix avtar", buttonBound: self.btnsuffix), for: .normal)
    

    OUTPUT WILL BE

提交回复
热议问题