随意细解:UI -- MVC、通知

MVC

  • Model(模型),存储、处理数据,为应⽤程序提供数据。
  • View(视图),展⽰⽤户界⾯视图,提供⽤户交互,展⽰模型提供的数据。
  • Controller(控制器),控制视图显⽰,处理⽤户交互,从模型获取数据展⽰在视图上。⺫的是解除模型和视图之间的耦合。

C 和 V 通信

  • C直接控制V
  • V向C发起通信的⽅式:
    - 设置View的target/action
    - 设置delegate
    - 设置dataSource
  • C负责处理V产⽣的事件

C 和 M 通信

  • C向M提出需求,直接使⽤M提供的数据。
  • M向C发起通信⽅式:KVO、通知,可以在M发⽣变化时通知C
  • C负责读取M提供的数据,负责监控M的变化并进⾏处理。

V 和 M 通信

  • V和M禁⽌通信
  • C负责M和V之间的通信。C从M获取数据,将数据显⽰在View上

MVC优势

  • 实现低耦合,减少视图和控制器之间复杂冗余的代码。
  • 提⾼重⽤性,多个视图可以共享⼀个模型,多个控制器可以共享⼀个视图。
  • 更易于维护,M、V、C独⽴,可以分别处理不同的变化。

通知

  • 通知模式:⼀个对象能够给其他任意数量的对象⼲播信息。对象之间可以没有耦合关系。
  • NSNotification(通知),封装了要⼲播的信息。
  • NSNotificationCenter(通知中⼼),管理注册接收消息对象,⼲播消息。
  • observer(观察者),需要监测⼲播信息的对象,即接收信息的对象。

发送通知步骤

1.想接到通知的界面 注册通知
2.发送通知(点击方法中)
3.注册完通知,要在适合位置 移除通知(一般 都再dealloc中)

注册

接收信息对象在通知中⼼进⾏注册,包括:信息名称、接收信息时的处理⽅法。(想接到通知的界面)

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(Notification:) name:@"EARTHQUAKE" object:nil];

注销

在dealloc方法中

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"EARTHQUAKE" object:nil];
    [super dealloc];
}

发送信息

object 发送人 可以不填
userInfo 发送通知 携带的数据

// 构建字典
NSDictionary *dic = @{@"name":@"dj"};
[[NSNotificationCenter defaultCenter] postNotificationName:@"EARTHQUAKE" object:self userInfo:dic];

更换皮肤

换皮肤就相当于更换一下根视图控制器。在APPDelegate中的- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions方法中编写代码。(在另一个页面设置一个button,点击方法中发送通知。)

  1. 设置根视图

    RootViewController *rootVc = [[RootViewController alloc]init];
    UINavigationController *navCon = [[UINavigationController alloc]initWithRootViewController:rootVc];
    self.window.rootViewController = navCon;
    [rootVc release];
    [navCon release];
    
  2. 注册通知

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Notification:) name:@"CHANGECOLOR" object:nil];
  3. 选择器Notification方法

    - (void)Notification:(NSNotification *)notification
    {
         // 1.获取根视图控制器
        UIViewController *rootVC = self.window.rootViewController;
        // 2.取消当前的根视图控制器
        self.window.rootViewController = nil;
    
        // 3.换肤 导航条 TabBar
        // appearance 可以把全部 导航条取出来
        UINavigationBar *navBar = [UINavigationBar appearance];
        // 修改颜色
       [navBar setBarTintColor:[UIColor cyanColor]];
       // 取出TabBar
       UITabBar *tabBar = [UITabBar appearance];
       [tabBar setBarTintColor:[UIColor cyanColor]];
        // 重新设置根视图控制器
        self.window.rootViewController = rootVC;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值