I'm trying to subclass UIButton
with my own button class called FlipsSendButton
. The code for this class is listed below. In it you can see that I am calling setImage
to attempt to set the button image. However, after compiling, everything works correctly EXCEPT setting the image view.
Am I missing some steps in my code to set the image, or perhaps calling the optional and unwrap operators incorrectly?
import Foundation
class FlipSendButton : UIButton {
let bgColor : UIColor
init(frame aFrame: CGRect, bgColor aColor: UIColor) {
bgColor = aColor;
super.init(frame: aFrame)
addTarget(self, action: Selector("buttonTouched:"), forControlEvents: .TouchUpInside)
backgroundColor = aColor;
setImage(UIImage(named: "flips.png") as UIImage?, forState: .Normal)
}
required init(coder aDecoder: NSCoder) {
bgColor = UIColor.lightGrayColor()
super.init(coder: aDecoder)
}
func buttonTouched(sender: UIButton) {
if backgroundColor == UIColor.lightGrayColor() {
backgroundColor = bgColor
} else {
backgroundColor = UIColor.lightGrayColor()
}
}
}
Also, it is worth mentioning that the image flips.png is in my images.xassets folder, if that makes a difference.
You forgot the
buttonType
property. Besides, you'd better not subclass theUIButton
(check out this for the reason).Instead, You should set the
buttonType
property toUIButtonTypeCustom
when you init the button, some sample code:-- EDIT --
If you want to reuse the style configuration, a better way is to define your own factory method of
UIButton
. Something like:Then you can use the button like: