【问题标题】:IOS How to access uipageviewcontroller from its children?IOS 如何从其子级访问 uipageviewcontroller?
【发布时间】:2023-03-26 05:51:01
【问题描述】:

我有以下类,第一个包含 UIPageViewController 的实例,第二个是孩子的视图控制器

@interface GuidePager : UIViewController     <UIPageViewControllerDataSource, UIPageViewControllerDelegate>
@property (strong, nonatomic) UIPageViewController *pageController;
@property NSArray *viewControllers;
- (void)flipToPage:(NSString *)index;

@end

@interface GuidePagerChild : UIViewController <UIWebViewDelegate>

@end

我需要从 GuidePagerChild 中的 GuidePagerChild 调用 GuidePager 的 flipToPage。

请帮忙。

【问题讨论】:

    标签: ios uipageviewcontroller


    【解决方案1】:

    为孩子添加一个委托协议:

    @protocol GuidePagerChildDelegate;
    
    @interface GuidePagerChild : UIViewController <UIWebViewDelegate>
    @property (nonatomic, weak) id<GuidePagerChildDelegate> delegate;   
    @end
    
    @protocol GuidePagerChildDelegate <NSObject>
    @required
    - (void)guidePagerChild:(GuidePagerChild *)child flipToPage:(NSString *)index
    @end
    

    然后:

    @interface GuidePager : UIViewController <
        GuidePagerChildDelegate,  // Add the new protocol to the list.
        UIPageViewControllerDataSource, 
        UIPageViewControllerDelegate
    >
    @property (strong, nonatomic) UIPageViewController *pageController;
    @property NSArray *viewControllers;
    - (void)flipToPage:(NSString *)index;
    
    @end
    

    那么当你创建孩子时:

    GuidePagerChildDelegate *child = [[GuidePagerChild alloc] init];  // Or however you create it.
    child.delegate = self;  // Assuming you create it from within GuidePager.  If not, get a pointer to GuidePager and set it as the delegate.
    

    然后:

    @implementation GuidePager
    
    ...
    
    - (void)guidePagerChild:(GuidePagerChild *)child flipToPage:(NSString *)index 
    {
         [self flipToPage:index];
    }
    
    ...
    
    @end
    

    【讨论】:

    • 还有其他方法。例如,您可以触发NSNotification。一般来说,iOS 框架更喜欢委托模式。
    • 然后使用委托可能会阻止释放子页面(我遇到了这个)并使用太多内存。我通过使用通知解决了它。
    • 或者你可以解决内存问题。如果代理被弱引用并且没有任何东西保留它,那么内存泄漏就没有理由了。
    猜你喜欢
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多