案例1
KCButton.h//// KCButton.h// PRotocol&Block&Category//// Created by Kenshin Cui on 14-2-2.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h>@class KCButton;//一個(gè)協(xié)議可以擴(kuò)展另一個(gè)協(xié)議,例如KCButtonDelegate擴(kuò)展了NSObject協(xié)議@protocol KCButtonDelegate <NSObject>@required //@required修飾的方法必須實(shí)現(xiàn)-(void)onClick:(KCButton *)button;@optional //@optional修飾的方法是可選實(shí)現(xiàn)的-(void)onMouSEOver:(KCButton *)button;-(void)onMouseout:(KCButton *)button;@end@interface KCButton : NSObject#pragma mark - 屬性#pragma mark 代理屬性,同時(shí)約定作為代理的對象必須實(shí)現(xiàn)KCButtonDelegate協(xié)議@property (nonatomic,retain) id<KCButtonDelegate> delegate;#pragma mark - 公共方法#pragma mark 點(diǎn)擊方法-(void)click;@end
KCButton.m//// KCButton.m// Protocol&Block&Category//// Created by Kenshin Cui on 14-2-2.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import "KCButton.h"@implementation KCButton-(void)click{ NSLog(@"Invoke KCButton's click method."); //判斷_delegate實(shí)例是否實(shí)現(xiàn)了onClick:方法(注意方法名是"onClick:",后面有個(gè):) //避免未實(shí)現(xiàn)ButtonDelegate的類也作為KCButton的監(jiān)聽 if([_delegate respondsToSelector:@selector(onClick:)]){ [_delegate onClick:self]; }}@endMyListener.h//// MyListener.h// Protocol&Block&Category//// Created by Kenshin Cui on 14-2-2.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h>@class KCButton;@protocol KCButtonDelegate;@interface MyListener : NSObject<KCButtonDelegate>-(void)onClick:(KCButton *)button;@endMyListener.m//// MyListener.m// Protocol&Block&Category//// Created by Kenshin Cui on 14-2-2.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import "MyListener.h"#import "KCButton.h"@implementation MyListener-(void)onClick:(KCButton *)button{ NSLog(@"Invoke MyListener's onClick method.The button is:%@.",button);}@endmain.m//// main.m// Protocol&Block&Category//// Created by Kenshin Cui on 14-2-2.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h>#import "KCButton.h"#import "MyListener.h"int main(int argc, const char * argv[]) { @autoreleasepool { KCButton *button=[[KCButton alloc]init]; MyListener *listener=[[MyListener alloc]init]; button.delegate=listener; [button click]; /* 結(jié)果: Invoke KCButton's click method. Invoke MyListener's onClick method.The button is:<KCButton: 0x1001034c0>. */ } return 0;}
我們通過例子模擬了一個(gè)按鈕的點(diǎn)擊過程,有點(diǎn)類似于java中事件的實(shí)現(xiàn)機(jī)制。通過這個(gè)例子我們需要注意以下幾點(diǎn)內(nèi)容:id可以表示任何一個(gè)ObjC對象類型,類型后面的”<協(xié)議名>“用于約束作為這個(gè)屬性的對象必須實(shí)現(xiàn)該協(xié)議(注意:使用id定義的對象類型不需要加“*”);MyListener作為事件觸發(fā)者,它實(shí)現(xiàn)了KCButtonDelegate代理(在ObjC中沒有命名空間和包的概念,通常通過前綴進(jìn)行類的劃分,“KC”是我們自定義的前綴)在.h文件中如果使用了另一個(gè)文件的類或協(xié)議我們可以通過@class或者@protocol進(jìn)行聲明,而不必導(dǎo)入這個(gè)文件,這樣可以提高編譯效率(注意有些情況必須使用@class或@protocol,例如上面KCButton.h中上面聲明的KCButtonDelegate協(xié)議中用到了KCButton類,而此文件下方的KCButton類聲明中又使用了KCButtonDelegate,從而形成在一個(gè)文件中互相引用關(guān)系,此時(shí)必須使用@class或者@protocol聲明,否則編譯階段會報(bào)錯(cuò)),但是在.m文件中則必須導(dǎo)入對應(yīng)的類聲明文件或協(xié)議文件(如果不導(dǎo)入雖然語法檢查可以通過但是編譯鏈接會報(bào)錯(cuò));使用respondsToSelector方法可以判斷一個(gè)對象是否實(shí)現(xiàn)了某個(gè)方法(需要注意方法名不是”onClick”而是“onClick:”,冒號也是方法名的一部分);屬性中的(nonatomic,retain)不是這篇文章的重點(diǎn),在接下來的文章中我們會具體介紹。
案例2
//// WPContactsViewController.h// OC-UI-表單-單元格//// Created by wangtouwang on 15/3/26.// Copyright (c) 2015年 wangtouwang. All rights reserved.//#import <UIKit/UIKit.h>@interface WPContactsViewController : UIViewController{ UITableView *_tableView;//表單UI控件 NSMutableArray *_mutableArrayContacts;//聯(lián)系人集合模型 NSIndexPath *_selectedIndexPath;//當(dāng)前選中的組和行}@end
//// WPContactsViewController.m// OC-UI-表單-單元格//// Created by wangtouwang on 15/3/26.// Copyright (c) 2015年 wangtouwang. All rights reserved.//#import "WPContactsViewController.h"#import "WPContacts.h"#import "WPContactsGroup.h"@interface WPContactsViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>@end@implementation WPContactsViewController- (void)viewDidLoad { [super viewDidLoad]; //初始化數(shù)據(jù) [self initObjectData]; //創(chuàng)建一個(gè)分組樣式的UITableView _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; //設(shè)置數(shù)據(jù)源,注意必須實(shí)現(xiàn)對應(yīng)的UITableViewDataSource協(xié)議 _tableView.dataSource=self; //設(shè)置代理 _tableView.delegate=self; [self.view addSubview:_tableView];}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}#pragma mark 加載數(shù)據(jù)-(void)initObjectData{ _mutableArrayContacts=[[NSMutableArray alloc]init]; WPContacts *contact1=[WPContacts initStaticWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"]; WPContacts *contact2=[WPContacts initStaticWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"]; WPContactsGroup *group1=[WPContactsGroup initStaticWithName:@"C" andDescript:@"With names beginning with C" andConcats:[NSMutableArray arrayWithObjects:contact1,contact2, nil]]; [_mutableArrayContacts addObject:group1]; WPContacts *contact3=[WPContacts initStaticWithFirstName:@"Dui" andLastName:@"JACK" andPhoneNumber:@"13712133321"]; WPContacts *contact4=[WPContacts initStaticWithFirstName:@"Dui" andLastName:@"LUCY" andPhoneNumber:@"13712133322"]; WPContactsGroup *group2=[WPContactsGroup initStaticWithName:@"D" andDescript:@"With names beginning with D" andConcats:[NSMutableArray arrayWithObjects:contact3,contact4, nil]]; [_mutableArrayContacts addObject:group2]; }#pragma mark 返回分組數(shù)-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ NSLog(@"計(jì)算分組數(shù)"); return _mutableArrayContacts.count;}#pragma mark 返回每組行數(shù)- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ NSLog(@"計(jì)算每組(組%lu)行數(shù)",(unsigned long)section);// WPContactsGroup *group1 = _mutableArrayContacts[section]; return ((WPContactsGroup *)_mutableArrayContacts[section])._concats.count;}#pragma mark返回每行的單元格- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ NSLog(@"生成單元格(組:%lu,行%lu)",(unsigned long)indexPath.section,(unsigned long)indexPath.row); WPContactsGroup *group= _mutableArrayContacts[indexPath.section]; WPContacts *contacts = group._concats[indexPath.row]; UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil]; cell.textLabel.text=[contacts getName]; cell.detailTextLabel.text = [contacts _phoneNumber]; return cell;}#pragma mark 返回每組頭標(biāo)題名稱- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ NSLog(@"生成組(組%lu)名稱",(unsigned long)section); WPContactsGroup *group = _mutableArrayContacts[section]; return group._name;}#pragma mark 返回每組尾部說明- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{ NSLog(@"生成尾部(組%lu)詳情",(unsigned long)section); return ((WPContactsGroup *)_mutableArrayContacts[section])._descript;}#pragma mark 生成索引- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{ NSLog(@"生成組索引"); NSMutableArray *indexs = [[NSMutableArray alloc] init]; for (WPContactsGroup *group in _mutableArrayContacts) { [indexs addObject:group._name]; } return indexs;}#pragma mark 設(shè)置分組標(biāo)題高度- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{ NSLog(@"設(shè)置分組標(biāo)題高度"); return 25;}#pragma mark 設(shè)置分組尾部內(nèi)容高度- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{ NSLog(@"設(shè)置分組尾部內(nèi)容高度"); return 20;}#pragma mark 設(shè)置每行高度- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ NSLog(@"設(shè)置每行高度"); return 30;}#pragma mark 復(fù)寫設(shè)置點(diǎn)擊行觸發(fā)事件(復(fù)寫的方法是在TableViewDelegate協(xié)議中已有,回調(diào))-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ NSLog(@"觸發(fā)我吧"); _selectedIndexPath=indexPath; //獲取單元格包裝的對象WPContacts WPContacts *contacts = ((WPContactsGroup *)_mutableArrayContacts[indexPath.section])._concats[indexPath.row]; //初始化彈出框 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"System Info" message:[contacts getName] delegate:self cancelButtonTitle:@"Cancle" otherButtonTitles:@"OK", nil]; //設(shè)置窗口樣式 alertView.alertViewStyle=UIAlertViewStylePlainTextInput; //獲取文本框 UITextField *textFild = [alertView textFieldAtIndex:0]; //設(shè)置文本框內(nèi)容 textFild.text = contacts._phoneNumber; //顯示窗口 [alertView show];}#pragma mark 設(shè)置彈出框后續(xù)按鈕事件 復(fù)寫UIAlerViewDelegate協(xié)議 的點(diǎn)擊按鈕 clickedButtonAtIndex方法- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ NSLog(@"設(shè)置彈出框后續(xù)按鈕事件 clickedButtonAtIndex"); if (buttonIndex==1) { //獲取文本框內(nèi)容 NSString *phoneNumber = [alertView textFieldAtIndex:0].text; //獲取選中的UITableViewCell 包裝的對象 WPContacts *contacts = ((WPContactsGroup *)_mutableArrayContacts[_selectedIndexPath.section])._concats[_selectedIndexPath.row]; contacts._phoneNumber = phoneNumber; NSArray *indexPaths=@[_selectedIndexPath];//需要局部刷新的單元格的組、行 //此處優(yōu)化 將全局跟新 該變到 選擇行 局部更新 [_tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft]; //[_tableView reloadData]; }}@end
新聞熱點(diǎn)
疑難解答
圖片精選