Home:ALL Converter>IOS Accessing one view from another view

IOS Accessing one view from another view

Ask Time:2013-01-07T13:55:56         Author:mayy00

Json Formatter

Basically I have a view controller having two subviews. I want these views to be connected. A touch event should trigger an event from another view and vice versa. I have thought about two solutions.

1-) Accessing views through their view controllers

2-) Each view has a pointer to another view

I am a newbie on IOS and as far I read from other problems it is mentioned that accessing view controller from a view is not suggested. So, what do you guys suggest me to do?

Edit:

I didn't make much progress on coding but my first view is:

@interface PaintView : UIView
-(id)initWithFrame:(CGRect)frame andController:(ViewController*)ctrl;

and i will control the touch event and access my viewcontroller:

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
     //[self.controller somethingThatAccessToOtherView]
}

and second view will be very similar to that one.

Author:mayy00,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/14190656/ios-accessing-one-view-from-another-view
Aatish Molasi :

Why dont you use the delegate pattern!\nFor the two views communicate with each other ..\nIts essentially similar to \" Each view has a pointer to another view\" but in a much more flexible manner \n\nhere is a so thread on it and ",
2013-01-07T06:24:11
Bergasms :

If you want the simplest, dirtiest, and non recommended way of proceeding. Tag your two views with some sort of unique tag (use say, -20 and -21, or something. So in the view controller where you create the views you do the following.\n\n[v1 setTag:-20];\n[v2 setTag:-21];\n\n\nThen you can do from in say, v2, the following.\n\n[self.superview viewWithTag:-20];\n\n\nto get a reference to v1. However, this assumes the same superview, and is not a nice way of doing things unless you are sure that the view heirachy will not change (I'm talking, it's a widget you made that no one else is going to touch and you've documented it well anyway). \n\nA better way would be to use a delegate pattern. The ViewController is the delegate of each of the subviews. On touch, the subviews call some method like \n\n[delegate iwastouched:self];\n\n\nand the delegate has a method like\n\n-(void) iwastouched:(UIView *) someview {\n if(someview == v1){\n //view 1 was touched, do something to view two\n }\n if(someview == v2){\n //view 2 was touched, do something to view one\n } \n}\n\n\nAnother bad way of doing it would be to use notifications. Hell, there are about as many ways to do this as you could like. Some are just not as nice.",
2013-01-07T06:28:38
yy