IBDesignableを使用して、UIButtonで左右の画像を左右に表示するにはどうすればいいですか?Swift 3.0のIBDesignableを使用して左右の画像を持つUIButton
私はグーグルで答えを見つけようとしましたが、スマートな答えは見つかりませんでした。ストーリーボードでやりたい
IBDesignableを使用して、UIButtonで左右の画像を左右に表示するにはどうすればいいですか?Swift 3.0のIBDesignableを使用して左右の画像を持つUIButton
私はグーグルで答えを見つけようとしましたが、スマートな答えは見つかりませんでした。ストーリーボードでやりたい
あなたがこの上に構築することができます
必要な出力を助けてください。属性インスペクタでボタンを設定した後、この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)
}
}
あなたはそれが迅速な解決とnot fully tested
だだけ例えば選択右の画像が、なし左画像などがあるでしょうときのケースを確認してください。 楽しさと幸運をお持ちです! ;]
すべてのエッジケースをチェックするのを忘れないでください???この行はどういう意味ですか?説明してください。 @Oleh –
このクラスは左右の画像を与えますが、タイトルは付けません。 –
私のために働いていません –
タイトルテキストセットのボタンイメージを取ることができますContentInsets またはボタンのイメージビューを取得してconstartaintを設定することができます –