Swift: Custom UIButton Class in View Controller Touch Event Not Trigger?
You may need a closure not a computed property
lazy var customBtn: CustomButton = {
let frame = CGRect(x: 48.0, y: 177.0, width: 80.0, height: 40.0)
let custom = CustomButton(frame: frame, title: "Test",alignment: NSTextAlignment.right)
return custom
}()
Here inside MainViewController
customBtn.addTarget(self,
action: #selector(touchCancel),
for: .touchUpInside)
you add the target to a newly created instance not to the one you added as a subview and it's the main difference between your implementation ( computed property ) and closure
why is my custom UIButton subclass not triggering touch up IBAction?
ah ok, figured it out. in my custom button initializer I added a subview which, by default, had userInteractionEnabled set to true. setting userInteractionEnabled = true
on my custom button object and userInteractionEnabled = false
on my view before adding it as a subview allows my custom button to capture the touch and handle it properly rather than the view capturing the touch
Custom UIButton class with animation swift
You can do something like below, just replace the event which ever you are interested in.
class AnimatedButton: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
self.addTarget(self, action: #selector(AnimatedButton.buttonClicked(sender:)), for: .touchUpInside)
}
@objc private func buttonClicked(sender: UIButton) {
sender.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
// animation ...
}
}
Subclassing UIButton and overriding touch events - not working
Instead of calling super in the completion block of touchesCancelled
and touchesEnded
methods I called self.sendActionsForControlEvents(UIControlEvents.TouchUpInside)
in there.
Rounded Custom UIButton does not exhibit the touch effect
You could add Animation on the button touch event to achieve the effect as you need . For example , set the BackgroundColor gradient .
public class RoundButton : UIButton
{
public override void LayoutSubviews()
{
base.LayoutSubviews();
Layer.CornerRadius = Bounds.Height / 2;
}
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
this.Highlighted = true;
SetAnimation(UIColor.LightGray);
base.TouchesBegan(touches, evt);
}
public override void TouchesEnded(NSSet touches, UIEvent evt)
{
this.Highlighted = false;
SetAnimation(UIColor.Orange);
base.TouchesEnded(touches, evt);
}
public override void TouchesCancelled(NSSet touches, UIEvent evt)
{
this.Highlighted = false;
base.TouchesCancelled(touches, evt);
}
void SetAnimation(UIColor color)
{
UIView.BeginAnimations(null);
UIView.SetAnimationDuration(1.0);
UIView.SetAnimationTransition(UIViewAnimationTransition.None, this, false);
this.Layer.BackgroundColor = color.CGColor;
UIView.CommitAnimations();
}
}
For more details about Animations in iOS you could check the doc .
Subclassing UIButton to handle clicks
I think there are better solutions to this problem than what you've proposed, but to answer your question directly: A subclass of UIButton observes touch events the same way that everyone else observes touch events.
// In your UIButton subclass
- (instancetype)initWithFrame:(CGRect)frame {
self = [super buttonWithType:UIButtonTypeCustom];
if (self) {
[self addTarget:self action:@selector(didTouchButton) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (void)didTouchButton {
// do whatever you need to do here
}
Important note: you can't use [UIButton buttonWithType:]
to create your button, you've got to use init
or initWithFrame:
. Even though UIButton has the convenience initializer, initWithFrame:
is still the designated initializer.
Related Topics
How to Integrate Fitbit API in iOS App Using Swift
How to Send a Request with Alamofire with Xml Body
How to Properly Handle a Nil Uiapplication.Sharedapplication().Keywindow
Updating the Status Bar Style Between View Controllers
Updating Label Takes Too Long (Swift)
iOS Sharecontext Tapping on Suggestion Intent Property of Extensioncontext Is Nil
Pass Data from Tableview to Tab Bar View Controller in Swift
Sharing Image and Text to Facebook Messenger with Uiactivityviewcontroller Failing
Lineargravityfield() Is Not Affecting Physics Bodies in the Scene Scenekit
How Should Secure Transport Tls Be Used with Bsd Sockets in Swift
Swift 3:Url Image Makes Uitableview Scroll Slow Issue
Uitapgesturerecognizer Called Immediately
Disable Long Press Back Button (Callout Menu)
Error When Trying to Save a Captured Image in Swift
Coredata Conditionally Fetching on Nsdate Using Nspredicate (Swift)
Random Number from an Array Without Repeating the Same Number Twice in a Row
How to Make Playground Execution Time Is as Fast as If We Run in iOS Application