Referencing objects programmatically which were set up with Interface Builder
I have set up several Views each containing a UIPickerView each of which contains a UIToolbar, and each of which in turn has a UIBarButtonItem. All this is set up in IB. I have pointers to the UIPickerViews in the code. I am needing to reference the UIBarButtonItems as part of a function that behaves differently depending on which of the UIPickerViews it is dealing with. I have the (id) sender as an argument to this function. The sender is always one of the UIBarButtonItems. I am trying to find which UIPickerView this particular UIBarButtonItem belongs to. I assume that I have to start up the UIPickerView hierarchy and work down to the UIBarButtonItem. I think this is the correct approach because I cannot do a simple compare since I have no explicit reference to the UIBarButtonItem object since it was set up in IB. 开发者_如何学运维 Further, because the subviews do not have a pointer to their parent view I cannot work my way back up the hierarchy. Correct? If I am correct in my thinking to this point, do I: traverse the view hierarchy in each UIPickerView, find a UIToolBar and then find a UIBarButtonItem? What exactly do I check for at both the UIToolBar level and the UIBarButtonItem level - I mean do I perform an if statement checking to see if the object is of type UIToolBar or UIBarButtonItem respectively? How do I find the type of an object in an if statement?
A related but more general question is should I have just set this entire thing up in code so that I would have had an explicit reference to the UIBarButtonItem that I could have compared the (id)sender against in the first place?
To figure out which one it is you need to do two things:
One. In code, add IBOutlet <object-type> <var-name>
to the @interface
. For example if you have a UIButton for "pause", you might do
@interface blabla {
...
IBOutlet UIButton btnPause;
}
Two. In Interface Builder, ctrl-drag from "File's Owner" to the button and select "btnPause".
In the place where you get (id)sender
, you can then do e.g.
if (sender == btnPause) { ... }
精彩评论