使用Swift 3.0中的IBDesignable在左侧和右侧使用图像的UIButton

Sou*_*rma 1 uibutton ios autolayout ibdesignable swift3

如何使用IBDesignable在UIButton中使用文本在左侧和右侧显示左右图像?

我试图谷歌它找到任何答案,但没有找到任何明智的答案.我想通过故事板来做到这一点.请帮忙

要求输出:

输出图像

Ole*_*ats 5

你可以在此基础上建立.在Attributes Inspector中设置按钮后,这个解开按钮的子类将重置标题并将图像放在两侧(不要忘记检查所有边缘情况):

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var button: DoubleImageButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        button.layer.borderWidth = 2.0
        button.layer.borderColor = UIColor.black.cgColor
        button.layer.cornerRadius = button.bounds.height*0.5
    }
}


@IBDesignable
class DoubleImageButton: UIButton {
    /* Inspectable properties, once modified resets attributed title of the button */
    @IBInspectable var leftImg: UIImage? = nil {
        didSet {
            /* reset title */
            setAttributedTitle()
        }
    }

    @IBInspectable var rightImg: UIImage? = nil {
        didSet {
            /* reset title */
            setAttributedTitle()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setAttributedTitle()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setAttributedTitle()
    }

    private func setAttributedTitle() {
        var attributedTitle = NSMutableAttributedString()

        /* Attaching first image */
        if let leftImg = leftImg {
            let leftAttachment = NSTextAttachment(data: nil, ofType: nil)
            leftAttachment.image = leftImg
            let attributedString = NSAttributedString(attachment: leftAttachment)
            let mutableAttributedString = NSMutableAttributedString(attributedString: attributedString)

            if let title = self.currentTitle {
                mutableAttributedString.append(NSAttributedString(string: title))
            }
            attributedTitle = mutableAttributedString
        }

        /* Attaching second image */
        if let rightImg = rightImg {
            let leftAttachment = NSTextAttachment(data: nil, ofType: nil)
            leftAttachment.image = rightImg
            let attributedString = NSAttributedString(attachment: leftAttachment)
            let mutableAttributedString = NSMutableAttributedString(attributedString: attributedString)
            attributedTitle.append(mutableAttributedString)
        }

        /* Finally, lets have that two-imaged button! */
        self.setAttributedTitle(attributedTitle, for: .normal)
    }
}
Run Code Online (Sandbox Code Playgroud)

在属性检查器中: 在此输入图像描述

结果(调整我的实现以获得最佳结果): 在此输入图像描述

例如,当您只选择了正确的图像但没有左图像等时,请务必检查案例.这是一个快速的解决方案not fully tested.玩得开心,祝你好运!]