代码之家  ›  专栏  ›  技术社区  ›  satyanarayana

带有自定义视图的iOS MVC实现

  •  1
  • satyanarayana  · 技术社区  · 10 年前

    当视图很简单时,它们的IBAction和IBoutlets位于viewcontroller中,viewcontroller会分配要加载的相应模型,并在准备好模型时通知viewcontroller。

    由于我的项目包含每个视图控制器的许多自定义视图,我希望在自定义视图本身中实现操作,并从控制器(viewcontroller)中设置数据。 我应该能够在iPhone和iPad上使用相同的控制器和型号,只有UI改变。

    我关心的是,当模型更改时,如何将数据从视图传递到视图控制器,并在视图上显示数据?

    是否有人可以建议我在视图之间传递数据<--->viewcontroller(控制器)<--->模型

    2 回复  |  直到 10 年前
        1
  •  2
  •   KIDdAe    6 年前

    为此,我使用委托设计模式。它看起来像这样:

    我的视图.h

    @protocol MyViewDelegate <NSObject>
    - (void)customViewDidSomething;
    @end
    
    @interface MyView : UIView
    
    @property (nonatomic, assign) id<MyViewDelegate> delegate
    
    @end
    

    我的视图.m

    - (void)userDidSomething {
       [_delegate customViewDidSomething];
    }
    

    MyViewController.h

    #import "MyView.h"
    
    // ViewController has to implement the protocol
    @interface MyViewController <MyViewDelegate>
    
    @property (nonatomic, retain) IBOutlet MyView myView;
    

    MyViewController.m

    - (void)viewDidLoad { // Set the delegate somewhere
       _myView.delegate = self
    }
    
    - (void)customViewDidSomething {
       // Ok VC is aware that something happened
       // Do something (tell subview to do something ?)
    }
    
        2
  •  0
  •   NKB    10 年前

    不要使用不同的自定义视图,请尝试使用UIViewController,然后使用视图控制器的视图显示UI。此外,这也将确保您能够在视图和控制器之间高效地进行通信,而不会产生混淆。