开发者

How do you connect events in view controllers created entirely in code, no Interface Builder?

开发者 https://www.devze.com 2023-02-22 16:48 出处:网络
I have created a UINavigationController with a UINavigationBar that has a UIBarButtonItem in the right position ENTIRELY in code, there is no IB/.xib file.

I have created a UINavigationController with a UINavigationBar that has a UIBarButtonItem in the right position ENTIRELY in code, there is no IB/.xib file.

As a newcomer开发者_开发问答 to XCode (v4) from C# I am trying to understand how to trap and handle the click event of the button in the navigation bar.

In C# there would be a click event that you would override which would contain the event handling code.

I have found a number of samples that use the IB to connect UI objects such as a button to a method in the view controller. However, I can not find any examples of how to achieve that solely in code.

Any references of insights appreciated.


In your viewDidLoad method create the UIBarButtonItem using one of the following initialisers...

– initWithImage:style:target:action:
– initWithTitle:style:target:action:

The last two parameters to the initialisers allow you to specify the object to invoke when the action occurs and the method on that object to call i.e.

UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(methodForItem:)];

Apple's UIBarButtonItem Class Reference


You'll want to use Target/Action on the right bar button item. So after you instantiate your UIBarButtonItem you'll do something like this.

[barButtonItem addTarget:self action:@selector(methodThatShouldBeCalled:) forControlEvents:UIControlEventTouchUpInside];

0

精彩评论

暂无评论...
验证码 换一张
取 消