iOS 協議使用

來源:互聯網
上載者:User

iOS 協議使用
這整個是一個cell,框框的放的image(有很多圖片,可以左右滑動,我用iCarousel做的,這個的代理寫在自訂cell類裡面的)。現在需要點擊圖片進入下一個頁面。。。。現在我點擊圖片,都會進入到自訂cell類裡面的代理裡,但是cell類裡面,是不讓我彈出下一個viewcontroller的。。??不然用[self.navigationController pushViewController:show animated:YES];這個方法。


最後用協議實現。當使用者點擊一個圖片的時候,進入到cell類的iCarousel代理方法-(void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index在這裡把index傳給StarShowViewController,然後在StarShowViewController裡面做push的動作。

(1)定義協議ImageItemDelegate.h#import

@protocol ImageItemDelegate

-(void)passItem:(NSString*)index;//把點擊的是第幾個image 的index 傳過來

@end



(2)在StarShowViewController.h類裡面遵守協議
#import "ImageItemDelegate.h"
@interface StarShowViewController : UIViewController {

UITableView *starTableView;
NSMutableArray *starArray;


}



(4)在StarShowTableViewCell.h類裡面聲明一個代理
#import "ImageItemDelegate.h"

@interface StarShowTableViewCell : UITableViewCell

@property(nonatomic,retain)NSObject *itemDelegate;//聲明一個代理


(5)在StarShowTableViewCell.m類裡面傳值

//選擇某個image item
-(void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index{

NSLog(@"index:%ld",(long)index);
NSString *str = [NSString stringWithFormat:@"%ld",index];


UIView *view = carousel.currentItemView;

[self.itemDelegate passItem:str];//通過代理把str傳到StarShowViewController類裡面


}


(6)在 StarShowViewController.m 裡面 表的代理方法 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath設定代理
cell.itemDelegate = self;//設定代理


(7)進入到下一個viewcontroller#pragma mark - ImageItemDelegate
//從cell那邊拿到值
-(void)passItem:(NSString *)index{

ShowViewController *show = [[ShowViewController alloc] init];
show.imageIdex = index;
[self.navigationController pushViewController:show animated:YES];

}



----------------------
叫你好好看書,又不好好看書! 實現方法很多種:①、可以在controller裡面直接給Image添加點擊事件 ②、使用delegate,在當前controller裡面實現即可觸發點擊事件 ③ block 簡單 ④ 事件響應者鏈可以處理
第一種在這裡不合適,第三種在這裡還沒有用過,理論上block也可以傳值,考慮到block限制比較多,不使用 第四種事件響應者鏈不太清楚是怎麼回事

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.