2017-03-22 34 views

回答

5

可以擴大戰果。在屬性檢查器中設置按鈕解開這個子類將在雙方重置標題和地點的圖像後(不要忘記檢查所有的特殊情況):

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) 
    } 
} 

在屬性檢查器中: enter image description here

結果(調整我的實現,以達到最佳的結果): enter image description here

一定要檢查情況下,當你必須選擇例如唯一正確的圖像,但沒有左圖像等,這是一個快速的解決方案和not fully tested。 玩得開心,祝你好運! ;]

+0

不要忘記檢查所有的邊緣情況???這條線是什麼意思?請解釋。 @Oleh –

+0

這個班給我左右圖像,但沒有標題。 –

+0

對我不起作用 –