简体   繁体   中英

IBAction or [UIButton addTarget:action: forControlEvents:] for UIButton created in .xib file? Which is the better approach?

What is the better approach if we are creating a UIButton in the .xib file using the Interface Builder, is it better to use IBAction method to define its Action Method and the required Control Event, or should we use

[UIButton addTarget:action: forControlEvents:] 

method to define the Action Method?

Which approach is better and why?

It depends upon user which one to use. Use xib to make easier and lots of code can be avoid to write.

Although any of the two can be used. The only reason I see it should be IBAction is because you have used xib. In this way you know that everything you have created is from xib. But once again, both are fine.

Yes. You can use any way.

Both of these methods begin with your existing eventreporter program. You'll add a simple UIButton to it using Interface Builder. Place the button a top the label at the bottom of your page and use the attributes tag to label it Reset. With it in place and defined, it's ready to be linked into your program by one of two different ways.

Using addTarget:action:forControlEvents: with a button

On the one hand, you may wish to add actions to your button programmatically. This could be the case if you created your button from within Xcode or if you created yourbutton in Interface Builder but want to change its behavior during runtime.Your first step is bringing your button into Xcode. If you created your button inInterface Builder, as we suggested earlier, you need to create an IBOutlet for the but-ton, which should be old hat by now. If you didn't create your button in InterfaceBuilder, you can do so in Xcode. This probably means using the factory class method buttonWithType: , which lets you create either a rounded rectangle button or one of afew special buttons, like the info button. By either means, you should now have a but-ton object available in Xcode.

Using an IBAction with a button

The other way you can link up actions to methods is to do everything inside InterfaceBuilder. This is the preferred choice if you've created your object in Interface Builder(as we've suggested) and you're not planning to change its behavior at runtime.When you use this procedure, you don't need to make your button into an IBOutlet. It's effectively invisible from Xcode, which is fine, because all you careabout is what happens when the button is pushed. You also don't use the somewhat complex addTarget:action:forControlEvents: method that we just ran through; instead, you connect things via intuitive Interface Builder means.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM