简体   繁体   中英

Passing data to ViewController from a custom view

My single view application on XCode has a custom view that is about half the size of the full iPhone screen. I have implemented a drawing tool that is only useable inside of the custom view. The custom view logs the distance the drawing tool was moved. With only one ViewController, I would like to display the distance variable in a Label outside of the custom fiew frame. Do I need to use protocols and delegates to do this? Or is there a much simpler way? I have been testing with the protocols and delegates method for the past few days and have not gotten anywhere.

First in the interface builder add your custom view as a subview of the main view constrollers view, also add the label. Then add outlets for the label and the view to the view controller (let's call them distanceLabel and drawView respectively).

Now declare distanceDrawn as a property of your custom view and when the tool is moved update it to contain the right number.

Then in the view controllers viewDidLoad you add:

    [drawView addObersver:self forKeyPath:@"distanceDrawn" options:NSKeyValueObservingOptionNew context:null]

Also add to the controller:

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        if ([object isEqual:drawView]) {
            id distance = change[NSKeyValueChangeNewKey]; //change to appropriate type
            distanceLabel.text = [NSString stringWithFormat:@"%@", distance];
        }
    }

Now whenever you change distanceDrawn this method will be called and the dictionary called change will contain the newly set value for the key NSKeyValueChangeNewKey . If you retrieve the value you can update the label.

Your custom view should have a property for the drawing length. You can then read the value from any class that has a reference to the custom view.

Probably you also want to have the view controller update the label every time the drawing length increases. You could handle that with Key-Value Observing. You register for notifications from the custom view object when its drawingLength property changes.

You could do this with a delegate. In some cases I think that's a cleaner solution. It's nice to make clear what sort of updates you can listen for from the custom view. However, this kind of case is just what Key-Value Observing is intended for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM