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

UIButton with image on left and right side using IBDesignable in Swift 3.0

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

我试图 google 它找到任何答案,但没有找到任何聪明的答案。我想通过故事板来完成。请帮忙

要求输出:

您可以以此为基础。在 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)
    }
}

在属性检查器中:

结果(调整我的实现以获得最佳结果):

请务必检查您只选择右图而没有选择左图等的情况。这是一个快速的解决方案 not fully tested。 玩得开心,祝你好运! ;]