如何使用IBDesignable在UIButton的左側和右側顯示左右圖像?UIButton在Swift 3.0中使用IBDesignable在左側和右側使用IBDesignable
我試圖谷歌它找到任何答案,但沒有找到任何明智的答案。我想通過故事板來完成。請幫助
所需的輸出:
如何使用IBDesignable在UIButton的左側和右側顯示左右圖像?UIButton在Swift 3.0中使用IBDesignable在左側和右側使用IBDesignable
我試圖谷歌它找到任何答案,但沒有找到任何明智的答案。我想通過故事板來完成。請幫助
所需的輸出:
可以擴大戰果。在屬性檢查器中設置按鈕解開這個子類將在雙方重置標題和地點的圖像後(不要忘記檢查所有的特殊情況):
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 –