您好,登錄后才能下訂單哦!
小編給大家分享一下IOS開(kāi)發(fā)之Target-Action模式有什么用,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
該模式主要是為了減少模塊之間代碼耦合性,以及增強(qiáng)模塊內(nèi)代碼之間的內(nèi)聚性.
讓我們來(lái)看看一個(gè)實(shí)例:
1:假設(shè)有這么一個(gè)需求:我們點(diǎn)擊一個(gè)視圖對(duì)象,可以改變?cè)撘晥D的顏色,這個(gè)對(duì)于初學(xué)者來(lái)說(shuō)是一件非常容易做到的事,只要在這個(gè)視圖類(lèi)中重寫(xiě):
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event函數(shù),然后改變?cè)撘晥D的背景色即可,可是這時(shí)候又有了新的需求,一部分人需要在點(diǎn)擊該視圖改變?cè)撘晥D的顏色,一部分人需要在點(diǎn)擊該視圖時(shí)改變?cè)撘晥D的位置,為了讓不同對(duì)象執(zhí)行不同的事件,在實(shí)例化該視圖類(lèi)對(duì)象時(shí)需要指定該對(duì)象感興趣的事件,對(duì)于這個(gè)需求我們可以通過(guò)定義枚舉變量作為該對(duì)象的數(shù)據(jù)成員,并在初始化的時(shí)候指定枚舉值(即指定感興趣的事件),同時(shí)需要重寫(xiě)-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event函數(shù),讓它對(duì)不同的枚舉值,執(zhí)行不同的功能,假設(shè)這個(gè)時(shí)候我們又需要在點(diǎn)擊該視圖對(duì)象時(shí),執(zhí)行一個(gè)翻轉(zhuǎn)功能,我們得又去修改該視圖內(nèi)的具體實(shí)現(xiàn)功能,這樣代碼之間的耦合性就比較大,移植起來(lái)就很不方便(試想這樣的一個(gè)場(chǎng)景,假設(shè)別人的app需要你寫(xiě)好的這個(gè)視圖類(lèi),但是別人不需要你視圖類(lèi)中事件方法,則需要修改該視圖類(lèi),難免發(fā)生一些錯(cuò)誤),解決這個(gè)問(wèn)題的方法就是Target-Action模式,直接看代碼:
//主視圖頭文件
#import <UIKit/UIKit.h> @interface MainViewController : UIViewController @end
//主視圖實(shí)現(xiàn)
#import "MainViewController.h" #import "MyView.h" @implementation MainViewController -(id)init { self= [super init]; if (self) { } return self; } -(void)viewDidLoad { MyView * view1 = [[MyView alloc]initWithFrame:CGRectMake(10, 20, 100, 100) andTarget:self andAction:@selector(changeColor:)]; [self.view addSubview:view1]; MyView * view2 = [[MyView alloc]initWithFrame:CGRectMake(10, 20, 100, 100) andTarget:self andAction:@selector(moveFrame:)]; [self.view addSubview:view2]; } -(void)changeColor:(UIView *)aView { NSLog(@"buttonClick"); int red = arc4random()%255; int green = arc4random()%255; int blue = arc4random()%255; aView.backgroundColor = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0]; } -(void)moveFrame:(UIView *)aView { aView.frame = CGRectMake(arc4random()%320, arc4random()%480, 100, 100); } @end
//測(cè)試視圖類(lèi)頭文件
#import <UIKit/UIKit.h> @interface MyView : UIView { id _target; SEL _action; } -(id)initWithFrame:(CGRect)frame andTarget:(id)target andAction:(SEL)action; @property (assign,readwrite,nonatomic)id deledate; @end
////測(cè)試視圖類(lèi)實(shí)現(xiàn)
#import "MyView.h" @implementation MyView -(id)initWithFrame:(CGRect)frame andTarget:(id)target andAction:(SEL)action { self = [super initWithFrame:frame]; if (self) { _target = target; _action = action; } self.backgroundColor = [UIColor blueColor]; return self; } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [_target performSelector:_action withObject:self]; } @end
看完了這篇文章,相信你對(duì)“IOS開(kāi)發(fā)之Target-Action模式有什么用”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。