Get to UIViewController from UIView?

前端 未结 29 2079
一整个雨季
一整个雨季 2020-11-22 16:57

Is there a built-in way to get from a UIView to its UIViewController? I know you can get from UIViewController to its UIView

29条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 17:39

    This doesn't answer the question directly, but rather makes an assumption about the intent of the question.

    If you have a view and in that view you need to call a method on another object, like say the view controller, you can use the NSNotificationCenter instead.

    First create your notification string in a header file

    #define SLCopyStringNotification @"ShaoloCopyStringNotification"
    

    In your view call postNotificationName:

    - (IBAction) copyString:(id)sender
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:SLCopyStringNotification object:nil];
    }
    

    Then in your view controller you add an observer. I do this in viewDidLoad

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

    Now (also in the same view controller) implement your method copyString: as depicted in the @selector above.

    - (IBAction) copyString:(id)sender
    {
        CalculatorResult* result = (CalculatorResult*)[[PercentCalculator sharedInstance].arrayTableDS objectAtIndex:([self.viewTableResults indexPathForSelectedRow].row)];
        UIPasteboard *gpBoard = [UIPasteboard generalPasteboard];
        [gpBoard setString:result.stringResult];
    }
    

    I'm not saying this is the right way to do this, it just seems cleaner than running up the first responder chain. I used this code to implement a UIMenuController on a UITableView and pass the event back up to the UIViewController so I can do something with the data.

提交回复
热议问题