标签:ios
在任性的提高代码质量里面,上期小弟提到了关于代码质量最基本的问题:代码规范
那么在这一期里,小弟会写一下关于MVC的简单使用,那么废话不多说,一会儿直接上代码
Model类:
我们先创建几个属性来弄一下吧,这里如果有某种类型多种状态,请用枚举来弄
#import <Foundation/Foundation.h>
typedef enum : NSUInteger {
SWHButtonTypeNone,
SWHButtonTypeUp,
SWHButtonTypeDown,
} SWHButtonType;
@interface SWHModel : NSObject
@property (nonatomic, assign) NSInteger num;
@property (nonatomic, assign) SWHButtonType buttonUpType;
@endView类:本期只用常用的TableViewCell来做
我们在Cell里面加一个Button,然后在外面爆出对应的方法,最好是给Cell一个属性来获取对应的Model,这样我们用起来比较方便,但是我并不已建议重写model的setter方法来做UI的对应赋值
#import <UIKit/UIKit.h> #import "SWHModel.h" @class SWHTableViewCell; typedef void(^ButtonBlock)(BOOL isChanged); @protocol SWHTableViewCellDelegate <NSObject> - (void)tableViewCell:(SWHTableViewCell *)cell didTappedButton:(UIButton *)button block:(ButtonBlock)block; @end @interface SWHTableViewCell : UITableViewCell @property (nonatomic, assign) id<SWHTableViewCellDelegate> delegate; @property (nonatomic, strong) SWHModel *model; - (void)setInfoWithModel:(SWHModel *)model; @end
#pragma mark - Action
- (BOOL)isButtonTypeChanged {
if (SWHButtonTypeDown == [self.model buttonUpType]) {
NSLog(@"您已经踩过");
return YES;
} else if (SWHButtonTypeUp == [self.model buttonUpType]) {
NSLog(@"您已经顶过");
return YES;
}
return NO;
}
- (void)upActionButton:(UIButton *)button {
if ([self isButtonTypeChanged]) {
return;
}
[button setBackgroundColor:[UIColor redColor]];
[self.model setButtonUpType:SWHButtonTypeUp];
[self.numLabel setText:[NSString stringWithFormat:@"%ld", ++self.model.num]];
__weak SWHTableViewCell *weakSelf = self;
if ([self.delegate respondsToSelector:@selector(tableViewCell:didTappedButton:block:)]) {
[self.delegate tableViewCell:self didTappedButton:button block:^(BOOL isChanged) {
if (!isChanged) {
[button setBackgroundColor:[UIColor yellowColor]];
[weakSelf.numLabel setText:[NSString stringWithFormat:@"%ld", --weakSelf.model.num]];
[weakSelf.model setButtonUpType:SWHButtonTypeNone];
}
}];
}
}Controller类:
正常来讲,我们需要在Controller里面来做请求网络并且对返回的数据进行存储并且将其赋值给对应的Cell,请不要在Controller里面来改变Cell的UI,那么我在这里做的是模仿虚拟网络,没有写真正的网络请求,思路大同小异了
#pragma mark - SWHTableViewCellDelegate
- (void)tableViewCell:(SWHTableViewCell *)cell didTappedButton:(UIButton *)button block:(ButtonBlock)block {
__weak ViewController *weakSelf = self;
__block ButtonBlock newBlock = block;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
newBlock([weakSelf delayRequest]);
});
}
#pragma mark - Method
- (BOOL)delayRequest {
NSInteger num = random() % 2;
if (num) {
NSLog(@"请求网络成功");
return YES;
}
NSLog(@"请求网络失败");
return NO;
}好啦,本期就写在这里咯,如果有什么好的建议,或者问题的话,请来群里哦,一起分享、探讨咱们的iOS技术咯
本文出自 “东软iOS校友群的技术博客” 博客,请务必保留此出处http://neusoftios.blog.51cto.com/9977509/1641627
标签:ios
原文地址:http://neusoftios.blog.51cto.com/9977509/1641627