views:

334

answers:

1

I have a question about tags for UIViews. Is it possible to create your own tag like myview.tag="main" or something like that?

I'm asking because my views are created in code and not with a nib file. After the container view has loaded and an xml file is fully parsed I need to be able to get at the subviews and update values.

After a bit of digging around I read that using viewWithTag would be a good way to do this

+3  A: 

Yes you can do that in your code and it is a common technique.

However, UIView-tag is an integer. So you might want to enum or define something readable e.g. #define kMySuperViewTag 1 or enum { kMySuperViewTag, kMyNotSoSuperViewTag, ...};

Till
hey cool, thanks.And how do I associate the tab with a view?
dubbeat
myView.tag = kMySuperViewTag; //(using defines or enums as explained)
Till
mega! Thanks alot
dubbeat
hmmmmm.....I can access my tabbarcontroller view no problem. When I try to get at one of its sub views my apps crashes UITabBarController *tabbar = nil; PromoTabOptionHome *home=nil; tabbar = (UITabBarController *)[self.view viewWithTag:79]; home=(PromoTabOptionHome *)[tabbar.view.subviews objectAtIndex:0]; //this line cause crash home.avatarPath=@"a test string";
dubbeat
Referring to your crash-problem; use the debugger:Set a breakpoint after that tabbar=...-line. Once the debugger stopped your application, go into the GDB-console and enter: "po tabbar". Is that object actually what you expected it to be? If the above has no surprising results, I would guess that your tabbar does not have any subviews attached at that moment.
Till
I figured out why it was crashing. My "PromoTabOptionHome" is actually a viewController not an actual view. I changed code to this and it worked UITabBar *tabbar = nil; UIView *home=nil; tabbar = (UITabBar *)[self.view viewWithTag:79]; tabbar.alpha=0.5; home=(UIView *)[tabbar.subviews objectAtIndex:0];.The problem now is I have access to the view I want but I cant access the methods in its controller like I wanted. Can I refer to the controller from some property of the view? E.G view.UIIController
dubbeat
Referring to your access UIViewController from inside its UIView; that is not supported by the plain UIView. If you insist on working that way you need to subclass UIView and add a reference to its UIViewController to it. Personally I find such construct not clever and would discourage its use as you were trashing reusability and creating strong dependencies on the UIView/UIViewController pairing. My rule of thumb: avoid accessing parent-objects from its childs if possible by any means. Certainly there are things were such construct makes sense but usually that is just sloppy coding.
Till
Ok, thanks very much for all of your advice. I reckon I should rethink how my code is working and do a little restructuring.
dubbeat