简体   繁体   中英

How can I hook up an IBAction method to a plain view for a touch up event?

I have created a blank new view-based application project in Xcode. It generated a myProjectViewController and an nib for it. In that nib for that view controller, there is just one view. I wanted to test some event handling stuff and created an -(IBAction) method that will just log a "hello world" when I touch the view. But for some reason, IB doesn't give me a chance to hook up the action. What am I doing wrong there? I also tried to put a UIView as subview there. When I drag from that to File's Owner (whoose class is the myProjectViewController, where I have the IBAction in the header), doesn't even mention the IBAction. But it actually should, right?

There is an easy way to achieve this. Goto your Interface builder of your class >> Select the view u want to add action to >> then change its custom class from IDENTITY INSPECTOR from UIView to 'UIControl'. Now u can add any IBAction method to this view.

将类更改为UIControl

将IBAction事件添加到此视图以执行操作方法

IBAction is just a tag that you add to a method declaration that identifies that method as a candidate for being connected to a control's action.

An IBAction method is the method that receives the action message of some other control.

UIViews don't send any actions. UIControls do. So there's nothing to hook up from a plain UIView to your object. You can only hook up IBActions to UIControl subclasses and UIBarButtonItems.

为此,我们有touchesBegan,touchesMoved和touchesEnded方法。

I think you can make use of the touchesBegan or touchesEnded method as @lostInTransit suggested. Its the proper way instead of making it as the view as a button.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

// do something here

}

IBAction are methods designed to receive an action from a control. They are not an indication to Interface Builder that the method is the source of an action (that the class generates in response to some other events).

To wire up custom events from a UIView subclass, see my answer to a related question here . You will need to use the delegate/protocol approach.

Make your view a class of UIButton. This will make the view hook-able.

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