2017-03-22 9 views
1

IBDesignableを使用して、UIButtonで左右の画像を左右に表示するにはどうすればいいですか?Swift 3.0のIBDesignableを使用して左右の画像を持つUIButton

私はグーグルで答えを見つけようとしましたが、スマートな答えは見つかりませんでした。ストーリーボードでやりたい

Output Image

+0

タイトルテキストセットのボタンイメージを取ることができますContentInsets またはボタンのイメージビューを取得してconstartaintを設定することができます –

答えて

5

あなたがこの上に構築することができます

必要な出力を助けてください。属性インスペクタでボタンを設定した後、このunbuttonサブクラスは、(すべてのエッジケースをチェックすることを忘れないでください)脇にタイトルと場所の画像をリセットします:属性インスペクタで

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

私のために働いていません –

関連する問題