在我的应用程序中,我想通过继承UIView创建自定义按钮,包括图标图像和标签。当用户点击按钮时,图标和标签颜色会发生变化,我会在其他课程中使用按下该按钮的信息。 (不是很重要)。
我创建了一个课程" @IBDesignable class IconButton: UIView{}
"我加载视图形式的xib文件。
有两个出口:
@IBOutlet var iconImageOutlet: UIImageView!
@IBOutlet var titleLabelOutlet: UILabel!
我希望我的按钮的标题和图像是IBInspectable。所以我这样做:
@IBInspectable var buttonText:String = "text_01"{
didSet{
titleLabelOutlet.text = buttonText
}
}
@IBInspectable var buttonImage:UIImage? = UIImage(named: "image_01"){
didSet{
iconImageOutlet.image = buttonImagesetColor()
}
}
我已经实现了这些方法来实例化视图:
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
override func prepareForInterfaceBuilder(){
super.prepareForInterfaceBuilder()
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
view.frame = boundsview.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(view)
setColor()
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "IconButton", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
private func setColor(){
iconImageOutlet.image = iconImageOutlet.image!.withRenderingMode(.alwaysTemplate)
UIView.animate(withDuration: 0.1) {
if self.isActive {
self.iconImageOutlet.tintColor = UIColor.pindexBlue()
self.titleLabelOutlet.textColor = UIColor.pindexBlue()
let changeColor = CATransition()
changeColor.type = kCATransitionFade
changeColor.duration = 0.1
CATransaction.begin()
CATransaction.setCompletionBlock {
self.titleLabelOutlet.textColor = UIColor.blue
self.titleLabelOutlet.layer.add(changeColor, forKey: nil)
}
self.titleLabelOutlet.textColor = UIColor.blue
self.titleLabelOutlet.layer.add(changeColor, forKey: nil)
CATransaction.commit()
} else {
self.iconImageOutlet.tintColor = UIColor.blue
self.titleLabelOutlet.textColor = UIColor.gray
let changeColor = CATransition()
changeColor.type = kCATransitionFade
changeColor.duration = 0.1
CATransaction.begin()
CATransaction.setCompletionBlock {
self.titleLabelOutlet.textColor = UIColor.gray
self.titleLabelOutlet.layer.add(changeColor, forKey: nil)
}
self.titleLabelOutlet.textColor = UIColor.gray
self.titleLabelOutlet.layer.add(changeColor, forKey: nil)
CATransaction.commit()
}
}
}
private var isActive:Bool = false
@IBAction func buttonPressed(_ sender: Any) {
isActive = !isActive
setColor()
}
我真的不知道自己做错了什么,也没有人接触到同样的问题。
所以,如果有人有假设,谢谢你:)
PS:抱歉我的英文不好