How do I add a IBAction to a button programmatically in Swift 4?
Swift 4 version:
button.addTarget(self, action: #selector(action(sender:)), for: .touchUpInside)
@objc private func action(sender: Button) {
print("test")
}
How to create an IBAction for a button programmatically-created based on user input
use addTarget to bind an action to a method
func buttonClicked(sender: UIButton){
print("button Clicked")
}
then add target to button
var button = UIButton()
button.addTarget(self, action: #selector(self.buttonClicked(sender:)), for: .touchUpInside)
How to add an action to a UIBarButton programmatically?
You can pass a target-action pair to the initialiser of UIBarButtonItem
:
let barButton = UIBarButtonItem(
image: UIImage(systemName: "bell.fill"),
style: .plain,
target: self, action: #selector(buttonTapped)
)
// somewhere in your view controller:
@objc func buttonTapped() {
// do something when the bar button is tapped
}
See the documentation here.
This is similar to UIButton
's addTarget(_:action:for:_)
method, if you are familiar with that.
Make a UIButton programmatically in Swift
You're just missing the colon at the end of the selector name. Since pressed takes a parameter the colon must be there. Also your pressed function shouldn't be nested inside viewDidLoad.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let myFirstLabel = UILabel()
let myFirstButton = UIButton()
myFirstLabel.text = "I made a label on the screen #toogood4you"
myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45)
myFirstLabel.textColor = .red
myFirstLabel.textAlignment = .center
myFirstLabel.numberOfLines = 5
myFirstLabel.frame = CGRect(x: 15, y: 54, width: 300, height: 500)
myFirstButton.setTitle("✸", for: .normal)
myFirstButton.setTitleColor(.blue, for: .normal)
myFirstButton.frame = CGRect(x: 15, y: -50, width: 300, height: 500)
myFirstButton.addTarget(self, action: #selector(pressed), for: .touchUpInside)
}
@objc func pressed() {
var alertView = UIAlertView()
alertView.addButtonWithTitle("Ok")
alertView.title = "title"
alertView.message = "message"
alertView.show()
}
EDIT: Updated to reflect best practices in Swift 2.2. #selector() should be used rather than a literal string which is deprecated.
IBAction & Buttons programmatically
The sender is testButn. You should change stayPressed's argument type from (id) to (UIButton *)
Unless an action method is connected to several different classes of objects, it's best to replace the id with whatever object class you're using. This can be useful if you're hooking things up in IB, since it won't let you hook it to the wrong kind of object.
The fact that it's not working isn't because it doesn't recognize your button. Your approach is wrong. I think you need to have an action connected to touch down, and maybe set the selected state to YES. In your button definition, you need to set an imageForState: for the selected state. The way you're doing it now, that method isn't called until touch up.
Something like this:
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton* testButn = [UIButton buttonWithType:UIButtonTypeCustom];
[testButn setFrame:CGRectMake(0, 135, 40, 38)];
[testButn setImage:[UIImage imageNamed:@"New_PICT0019.jpg"] forState:UIControlStateNormal];
[testButn setImage:[UIImage imageNamed:@"New_PICT0002.jpg"] forState:UIControlStateSelected];
[testButn addTarget:self action:@selector(stayPressed:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:testButn];
}
-(void)stayPressed:(UIButton *) sender {
if (sender.selected == YES) {
sender.selected = NO;
}else{
sender.selected = YES;
}
}
Swift add show action to button programmatically
You can go for below code
`
let btn: UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
btn.backgroundColor = UIColor.green
btn.setTitle("Click Me", for: .normal)
btn.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
btn.tag = 1
self.view.addSubview(btn)
for action
@objc func buttonAction(sender: UIButton!) {
let btnsendtag: UIButton = sender
if btnsendtag.tag == 1 {
dismiss(animated: true, completion: nil)
}
}
Related Topics
Create Navbar Programmatically with Button and Title Swift
iOS Swift Connect Wifi Programmatically and Distinguish Between Bad Password and No Wifi in Range
Libmobilegestalt Mobilegestalt.C:890: Mgisdeviceoneoftype Is Not Supported on This Platform
How to Keep the Header Cell Moving with the Tableview Cells in Swift 2.0
Uidropinteractiondelegate Performdrop Not Called
How to Trigger an API Call Before Displaying Local Notifications
Avaudiocompressedbuffer to Uint8 Array and Vice Versa
How to Make Synchronous Operation with Asynchronous Callback
Firebase Get Child Id Swift iOS
Gmsmarker Icon in the Top Left Corner of the View (Ios)
Adding Uigesturerecognizer to Subview Programmatically in Swift
How to Display Only Limited Photos with PHPickerviewcontroller
How to Use Multiple Protocols in Swift with Same Protocol Variables