代理、通知、KVO的应用
实现下图效果,每点击一次cell的“加号”或者“减号”,就可以让“底部view”的总价进行对应的增加或者减少。
下图是实际运行效果图:
图(1)
因为“底部UIView”需要一直显示在底部。如果把底部UIView添加到tableView上会导致其跟随tableView的滚动而滚动,所以不能把底部UIView作为tableView的子控件。所以把底部UIView添加到控制器的view上,让底部的UIView和tableView同级。如下图2展示了视图层级结构:
图(1)
方案一:KVO实现:
控制器监听数据模型中count属性的变化,进而根据count的增减做出不同的操作
步骤:
1.添加KVO监听
2.监听到键值变化后的操作
3.移除KVO监听
#import "ViewController.h"
#import "XMGWineCell.h"
#import "XMGWine.h"
#import "MJExtension.h" @interface ViewController () <UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIButton *buyButton;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/** 酒数据 */
@property (nonatomic, strong) NSArray *wineArray;
/** 总价 */
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
@end @implementation ViewController
- (NSArray *)wineArray
{
if (!_wineArray) {
self.wineArray = [XMGWine objectArrayWithFilename:@"wine.plist"]; for (XMGWine *wine in self.wineArray) {
// 添加KVO监听
[wine addObserver:self forKeyPath:@"count" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}
}
return _wineArray;
} - (void)viewDidLoad {
[super viewDidLoad]; }
#pragma mark - 移除KVO监听
- (void)dealloc
{
for (XMGWine *wine in self.wineArray) {
[wine removeObserver:self forKeyPath:@"count"];
}
} #pragma mark - KVO监听
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(XMGWine *)wine change:(NSDictionary *)change context:(void *)context
{
// NSKeyValueChangeNewKey == @"new"
int new = [change[NSKeyValueChangeNewKey] intValue];
// NSKeyValueChangeOldKey == @"old"
int old = [change[NSKeyValueChangeOldKey] intValue]; if (new > old) { // 增加数量
int totalPrice = self.totalPriceLabel.text.intValue + wine.money.intValue;
self.totalPriceLabel.text = [NSString stringWithFormat:@"%d", totalPrice];
self.buyButton.enabled = YES;
} else { // 数量减小
int totalPrice = self.totalPriceLabel.text.intValue - wine.money.intValue;
self.totalPriceLabel.text = [NSString stringWithFormat:@"%d", totalPrice];
self.buyButton.enabled = totalPrice > ;
}
}
方案二:通知:
步骤:
1.注册通知
2.添加监听
3.移除通知
1.在自定义cell的.m文件中注册通知:
#import "XMGWineCell.h"
#import "XMGWine.h"
#import "XMGCircleButton.h" @interface XMGWineCell()
@property (weak, nonatomic) IBOutlet XMGCircleButton *minusButton;
@property (weak, nonatomic) IBOutlet UIImageView *imageImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *moneyLabel;
@property (weak, nonatomic) IBOutlet UILabel *countLabel;
@end @implementation XMGWineCell - (void)setWine:(XMGWine *)wine
{
_wine = wine; self.imageImageView.image = [UIImage imageNamed:wine.image];
self.nameLabel.text = wine.name;
self.moneyLabel.text = wine.money;
self.countLabel.text = [NSString stringWithFormat:@"%d", wine.count];
self.minusButton.enabled = (wine.count > );
} /**
* 加号点击
*/
- (IBAction)plusClick {
// 修改模型
self.wine.count++; // 修改数量label
self.countLabel.text = [NSString stringWithFormat:@"%d", self.wine.count]; // 减号能点击
self.minusButton.enabled = YES; // 发布通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"plusClickNotification" object:self];
} /**
* 减号点击
*/
- (IBAction)minusClick {
// 修改模型
self.wine.count--; // 修改数量label
self.countLabel.text = [NSString stringWithFormat:@"%d", self.wine.count]; // 减号按钮不能点击
if (self.wine.count == ) {
self.minusButton.enabled = NO;
} // 发布通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"minusClickNotification" object:self];
}
@end
2.在控制器的.m文件中添加监听(在通知中心注册监听)
3.在控制器的dealloc方法中移除监听
#import "ViewController.h"
#import "XMGWineCell.h"
#import "XMGWine.h"
#import "MJExtension.h" @interface ViewController () <UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIButton *buyButton;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/** 酒数据 */
@property (nonatomic, strong) NSArray *wineArray;
/** 总价 */
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
@end @implementation ViewController
- (NSArray *)wineArray
{
if (!_wineArray) {
self.wineArray = [XMGWine objectArrayWithFilename:@"wine.plist"];
}
return _wineArray;
} - (void)viewDidLoad {
[super viewDidLoad]; // 监听通知
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(plusClick:) name:@"plusClickNotification" object:nil];
[center addObserver:self selector:@selector(minusClick:) name:@"minusClickNotification" object:nil];
} - (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
} #pragma mark - 按钮点击
- (IBAction)clear {
self.totalPriceLabel.text = @""; // 将模型里面的count清零
for (XMGWine *wine in self.wineArray) {
wine.count = ;
} // 刷新
[self.tableView reloadData]; self.buyButton.enabled = NO;
} - (IBAction)buy {
// 打印出所有要买的东西
for (XMGWine *wine in self.wineArray) {
if (wine.count) {
NSLog(@"%d件【%@】", wine.count, wine.name);
}
}
} #pragma mark - 监听通知
- (void)plusClick:(NSNotification *)note
{
self.buyButton.enabled = YES; // 取出cell(通知的发布者)
XMGWineCell *cell = note.object;
// 计算总价
int totalPrice = self.totalPriceLabel.text.intValue + cell.wine.money.intValue;
// 设置总价
self.totalPriceLabel.text = [NSString stringWithFormat:@"%d", totalPrice];
} - (void)minusClick:(NSNotification *)note
{
// 取出cell(通知的发布者)
XMGWineCell *cell = note.object;
// 计算总价
int totalPrice = self.totalPriceLabel.text.intValue - cell.wine.money.intValue;
// 设置总价
self.totalPriceLabel.text = [NSString stringWithFormat:@"%d", totalPrice]; self.buyButton.enabled = totalPrice > ;
}
方案三:delegate:
步骤:
1.制定代理协议
2.设置代理属性
3.遵守协议,实现代理方法
4.调用代理实现的协议方法
1.制定代理协议
2.设置代理属性
#import <UIKit/UIKit.h>
@class XMGWine, XMGCircleButton, XMGWineCell; @protocol XMGWineCellDelegate <NSObject>
@optional
- (void)wineCellDidClickPlusButton:(XMGWineCell *)wineCell;
- (void)wineCellDidClickMinusButton:(XMGWineCell *)wineCell;
@end @interface XMGWineCell : UITableViewCell
@property (strong, nonatomic) XMGWine *wine; /** 代理对象 */
@property (nonatomic, weak) id<XMGWineCellDelegate> delegate;
@end
自定义cell的.m文件中判断代理是否响应协议方法,如果响应,则调用代理实现的协议方法。
/**
* 加号点击
*/
- (IBAction)plusClick {
// 修改模型
self.wine.count++; // 修改数量label
self.countLabel.text = [NSString stringWithFormat:@"%d", self.wine.count]; // 减号能点击
self.minusButton.enabled = YES; // 通知代理(调用代理的方法)
// respondsToSelector:能判断某个对象是否实现了某个方法
if ([self.delegate respondsToSelector:@selector(wineCellDidClickPlusButton:)]) {
[self.delegate wineCellDidClickPlusButton:self];
}
} /**
* 减号点击
*/
- (IBAction)minusClick {
// 修改模型
self.wine.count--; // 修改数量label
self.countLabel.text = [NSString stringWithFormat:@"%d", self.wine.count]; // 减号按钮不能点击
if (self.wine.count == ) {
self.minusButton.enabled = NO;
} // 通知代理(调用代理的方法)
if ([self.delegate respondsToSelector:@selector(wineCellDidClickMinusButton:)]) {
[self.delegate wineCellDidClickMinusButton:self];
}
}
3.控制器的.m文件中遵守代理协议,实现协议方法
#import "ViewController.h"
#import "XMGWineCell.h"
#import "XMGWine.h"
#import "MJExtension.h" @interface ViewController () <UITableViewDataSource, XMGWineCellDelegate, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *buyButton;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/** 酒数据 */
@property (nonatomic, strong) NSArray *wineArray;
/** 总价 */
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel; /** 购物车对象(存放需要购买的商品) */
@property (nonatomic, strong) NSMutableArray *wineCar;
@end @implementation ViewController
- (NSMutableArray *)wineCar
{
if (!_wineCar) {
_wineCar = [NSMutableArray array];
}
return _wineCar;
} - (NSArray *)wineArray
{
if (!_wineArray) {
self.wineArray = [XMGWine objectArrayWithFilename:@"wine.plist"];
}
return _wineArray;
} - (void)viewDidLoad {
[super viewDidLoad]; } #pragma mark - <XMGWineCellDelegate>
- (void)wineCellDidClickMinusButton:(XMGWineCell *)wineCell
{
// 计算总价
int totalPrice = self.totalPriceLabel.text.intValue - wineCell.wine.money.intValue; // 设置总价
self.totalPriceLabel.text = [NSString stringWithFormat:@"%d", totalPrice]; self.buyButton.enabled = totalPrice > ; // 将商品从购物车中移除
if (wineCell.wine.count == ) {
[self.wineCar removeObject:wineCell.wine];
}
} - (void)wineCellDidClickPlusButton:(XMGWineCell *)wineCell
{
// 计算总价
int totalPrice = self.totalPriceLabel.text.intValue + wineCell.wine.money.intValue; // 设置总价
self.totalPriceLabel.text = [NSString stringWithFormat:@"%d", totalPrice]; self.buyButton.enabled = YES; // 如果这个商品已经在购物车中,就不用再添加
if ([self.wineCar containsObject:wineCell.wine]) return; // 添加需要购买的商品
[self.wineCar addObject:wineCell.wine];
}
代理、通知、KVO的应用的更多相关文章
- iOS开发——UI进阶篇(五)通知、代理、kvo的应用和对比,购物车
一.通知 1.通知中心(NSNotificationCenter)每一个应用程序都有一个通知中心(NSNotificationCenter)实例,专门负责协助不同对象之间的消息通信任何一个对象都可以向 ...
- ios通知-kvo
// KVC: Key Value Coding, 常见作用:给模型属性赋值 // KVO: Key Value Observing, 常用作用:监听模型属性值的改变 // // ViewCon ...
- [ 单例、代理 & 通知 ]
PS:手写单例.代理方法实现 & 通知的简单使用! [ 单例模式,代理设计模式,观察者模式! ] 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设 ...
- IOS第十天(1:QQ好友列表 ,自定义的headview,代理 ,通知 ,black的使用)
*****HMViewController.m #import "HMViewController.h" #import "HMFriendsGroupModel.h&q ...
- 使用注解配置Spring框架自动代理通知
话不多说上代码 项目架构图及Lib包如下: 第二步创建业务类接口 package cn.happy.day01.entity; /** * 1.业务接口 * @author Happy * */ pu ...
- Block实现代理/通知效果
例子1:A控制器->跳转—>B控制器 , 假设想从B控制器回传数组给A控制器 实现:B控制器.h文件定义一个block参数,.m文件执行block,A控制器设置block内容 B.h文件/ ...
- 线程间通信 GET POST
线程间通信有三种方法:NSThread GCD NSOperation 进程:操作系统里面每一个app就是一个进程. 一个进程里面可以包含多个线程,并且我们每一个app里面有且仅有一 ...
- OC 观察者模式(通知中心,KVO)
OC 观察者模式(通知中心,KVO) 什么是观察者模式??? A对B的变化感兴趣,就注册为B的观察者,当B发生变化时通知A,告知B发生了变化.这就是观察者模式. 观察者模式定义了一种一对多的依赖关系, ...
- IOS第二天-新浪微博 - 添加搜索框,弹出下拉菜单 ,代理的使用 ,HWTabBar.h(自定义TabBar)
********HWDiscoverViewController.m(发现) - (void)viewDidLoad { [super viewDidLoad]; // 创建搜索框对象 HWSearc ...
- iOS监听模式之KVO、KVC的高阶应用
KVC, KVO作为一种魔法贯穿日常Cocoa开发,笔者原先是准备写一篇对其的全面总结,可网络上对其的表面介绍已经够多了,除去基本层面的使用,笔者跟大家谈下平常在网络上没有提及的KVC, KVO进阶知 ...
随机推荐
- onSaveInstanceState() 和 onRestoreInstanceState()
本文介绍Android中关于Activity的两个神秘方法:onSaveInstanceState() 和 onRestoreInstanceState(),并且在介绍这两个方法之后,再分别来实现使用 ...
- Java命令行的执行参数
Java 程序命令行参数说明 启动Java程序的方式有两种: # starts a Java virtual machine, loads the specified class, and invok ...
- Linux下命令行安装配置android sdk
首先, 你得有个VPN 参考以下三篇完成Android SDK的安装 https://www.digitalocean.com/community/tutorials/how-to-build-and ...
- 安装ESXi5.5遇到Relocating modules and starting up the kernel的处理
在一些Dell较旧的服务器上安装ESXi 5.x时, 会遇到卡在Relocating modules and starting up the kernel过不去的问题. 比如我装的这台CS24VSS. ...
- web app iphone4 iphone5 iphone6 iphone6 Plus响应式布局 适配代码
来源:http://www.phptext.net/article_view.php?id=387 -------------------------------------------------- ...
- codevs 1033 蚯蚓的游戏问题
Description 在一块梯形田地上,一群蚯蚓在做收集食物游戏.蚯蚓们把梯形田地上的食物堆积整理如下: a(1,1) a(1,2)…a(1,m) a(2,1) a(2,2) a(2,3)…a ...
- python数字图像处理(16):霍夫圆和椭圆变换
在极坐标中,圆的表示方式为: x=x0+rcosθ y=y0+rsinθ 圆心为(x0,y0),r为半径,θ为旋转度数,值范围为0-359 如果给定圆心点和半径,则其它点是否在圆上,我们就能检测出来了 ...
- WPF 小技巧
在使用mvvm模式开发时,对于Command的绑定是一件很伤脑筋的事情,尽管有强大的Blend类库支持: xmlns:Custom="http://www.galasoft.ch/mvvml ...
- 如何在Vue2中实现组件props双向绑定
Vue学习笔记-3 前言 Vue 2.x相比较Vue 1.x而言,升级变化除了实现了Virtual-Dom以外,给使用者最大不适就是移除的组件的props的双向绑定功能. 以往在Vue1.x中利用pr ...
- mysql full text全文索引必要条件
show variables like 'ft_m%' 'ft_max_word_len', '84''ft_min_word_len', '4' 对于英文来说, ft_min_word_len=4是 ...