objective-c里的方法指针IMP的用法

本文介绍了一个自定义的iOS控件SGPopSelectView,该控件继承自UIView并实现了UITableView的功能,能够提供弹出菜单供用户选择,并通过delegate模式回调所选项目。文章还展示了如何在UIHotWordViewController中使用此控件。

SGPopSelectView.h

@interface SGPopSelectView : UIView

@property (nonatomic, assign) SEL selector;

@property (nonatomic, assign) IMP functionIMP;

@end

 

------------------------------------------------------------------------------------------------------------------------

SGPopSelectView.m

@interface SGPopSelectView () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@end 

@implementation SGPopSelectView

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{  

    _selectedIndex = indexPath.row;

    [tableView reloadData];    

    self.functionIMP(self, _selector, indexPath.row);//当选择菜单的某一项时,调用方法指针指向的方法

}

------------------------------------------------------------------------------------------------------------------------

UIHotWordViewController.h

#import <UIKit/UIKit.h>

#import "REMenu.h"

#import "SGPopSelectView.h"

 

@interface UIHotWordViewController : UIViewController

@property (strong,nonatomic) REMenu *menu;

@property (retain, nonatomic) IBOutlet UIButton *btnHotWord;

@property (nonatomic, strong) SGPopSelectView *popView;

@property (nonatomic, strong) NSArray *selections;

@property (nonatomic, retainNSString *r;

 @end

------------------------------------------------------------------------------------------------------------------------

UIHotWordViewController.m

- (void)viewDidLoad {

    [super viewDidLoad];    

    self.selections = @[@"句子",@"作品",@"作者"];

    self.popView = [[SGPopSelectView alloc] init];

    self.popView.selector = @selector(rows_selected:);//指定selector

    self.popView.functionIMP = [self methodForSelector:@selector(rows_selected:)];//指定函数指针

}

-(void) rows_selected:(NSInteger) idx {

    NSLog(@"选择了项%d", idx);//选择菜单后会调用此方法

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值