0

Is it possible to have a class change something on a View Controller without doing [ViewController alloc]init]?

I have a separate class calculating several things and I need to change the scrollView.contentInset on my ViewController as well as some other things.

Edit for a better explanation: My ViewController contains a scroll view with a text field at the bottom. When the user taps in that text field, I need to change the contentInset property of scrollView. I want to manage this all using a separate class (instead of having to do this in all of my View Controllers) so I need to be able to call scrollView.contentInset on the ViewController that is currently in view.

Baub
  • 5,004
  • 14
  • 56
  • 99

2 Answers2

0

If Mystery Object X needs a reference to a scrollview so it can send it a message, then you need to explicitly provide that reference in. In Mystery Object X's .h file, declare a @property for the scrollview. When you create MOX, set the scrollview property. Now MOX has the reference it needs.

jsd
  • 7,673
  • 5
  • 27
  • 47
  • So my `ViewController` has a `scrollView`. I can only declare a `@property` and use it if I call `[ViewController alloc]init]`from the remote class, which would not work correctly because the view would already be displayed. – Baub Dec 13 '11 at 20:04
0

I think of couple ways to handle this:

A. Using delegate method. B. NSNotificationCenter.

Let me know if you need to go into more detail.

Added code as requested:

To use NSNotificationCenter method:

Within the ViewController that has scrollView add an observer statement (perhaps in your viewDidLoad method), and create an method to change whatever property of scrollview you want to change:

-(void)viewDidLoad
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMethodToChangePropertyOfScrollview) name:@"ChangeScrollView" object:nil];
}

-(void)myMethodToChangePropertyOfScrollview
{
    //scrollView.contentInset = etc...
}

From whatever class you want to make the contentInset of that scrollView changed, just post a notification likes this:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeScrollView" object:nil];

To use the delegate method, you can use a similar example from one of my previous answer to another SO post. But in your case, I am not 100% sure what are relationship between those two classes.

Community
  • 1
  • 1
user523234
  • 14,323
  • 10
  • 62
  • 102
  • Please go into more detail. Keep in mind, I need to change a property on my `scrollView` in my `ViewController` from a completely separate class. – Baub Dec 13 '11 at 21:35