MVC变种代码
1、ViewController
#import "ViewController.h"
#import "JView.h"
#import "Model.h"
@interface ViewController ()<JHViewDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"begin");
JView *jview = [[JView alloc] init];
jview.delegate = self;
jview.frame = CGRectMake(100, 100, 100, 100);
[self.view addSubview:jview];
Model *model = [[Model alloc] init];
model.name = @"张三";
model.imageName = @"123";
jview.model = model;
NSLog(@"--");
}
- (void)appViewDidClick:(JView *)jview {
NSLog(@"点击了");
}
@end
2.Model
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Model : NSObject
@property (copy, nonatomic) NSString *imageName;
@property (copy, nonatomic) NSString *name;
@end
NS_ASSUME_NONNULL_END
#import "Model.h"
@implementation Model
@end
3.JView
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class Model,JView;
@protocol JHViewDelegate <NSObject>
- (void)appViewDidClick:(JView *)jview;
@end
@interface JView : UIView
@property (strong, nonatomic) Model *model;
@property (weak, nonatomic)id<JHViewDelegate> delegate;
@end
NS_ASSUME_NONNULL_END
#import "JView.h"
#import "Model.h"
@interface JView()
@property (weak, nonatomic) UIImageView *iconV;
@property (weak, nonatomic) UILabel *nameL;
@end
@implementation JView
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
UIImageView *iconV = [[UIImageView alloc] init];
iconV.frame = CGRectMake(0, 0, 100, 100);
[self addSubview:iconV];
_iconV = iconV;
UILabel *nameL = [[UILabel alloc] init];
nameL.frame = CGRectMake(0, 100, 100, 30);
nameL.textAlignment = NSTextAlignmentCenter;
[self addSubview:nameL];
_nameL = nameL;
}
return self;
}
- (void)setModel:(Model *)model {
_model = model;
self.iconV.image = [UIImage imageNamed:model.imageName];
self.nameL.text = model.name;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if ([self.delegate respondsToSelector:@selector(appViewDidClick:)]) {
[self.delegate appViewDidClick:self];
}
}
@end
|