一、代理的实现。 1.自己新建一个类。带.m和.h文件。 例如,新建好的类,如HMTabBar.在其内定义协议和代理。HMTabBar .h文件如下。 #import <UIKit/UIKit.h> @interface HMTabBar : UITabBar @end 2、这里需要在.h中定义协议。定义的协议,和属性。@class HMTabBar; @protocol HMTabBarDelegate <NSObject>//代理的名称:类名+Delegate @optional - (void)tabBarDidClickedPlusButton:(HMTabBar *)tabBar;//这是要代理要实现的方法。 @end 3、添加代理之后,完整的.h如下。
#import <UIKit/UIKit.h> @class HMTabBar; @protocol HMTabBarDelegate <NSObject> @optional - (void)tabBarDidClickedPlusButton:(HMTabBar *)tabBar; @end @interface HMTabBar : UITabBar @property (nonatomic, weak) id<HMTabBarDelegate> delegate; @end 4、.m文件跟平时的.m文件一下,设置跟平时一样。哪个类控制器需要这个代理。就要遵守响应的协议和代理。 .m文件内会有通知代理这一步骤。
// 通知代理 if ([self.delegate respondsToSelector:@selector(tabBarDidClickedPlusButton:)]) { [self.delegate tabBarDidClickedPlusButton:self]; } 5、哪个控制器需要这个代理,就要遵守这个代理。 这里,如HMTabBarViewController需要这个代理。 @interface HMTabBarViewController () <HMTabBarDelegate> 6、在HMTabBarViewController.m文件中需要设置代理。
// 创建自定义tabbar HMTabBar *customTabBar = [[HMTabBar alloc] init]; customTabBar.delegate = self;//设置代理。 7、实现代理相应的方法,即遵守的协议。 #pragma mark - HMTabBarDelegate - (void)tabBarDidClickedPlusButton:(HMTabBar *)tabBar { // 弹出发微博控制器 HMComposeViewController *compose = [[HMComposeViewController alloc] init]; HMNavigationController *nav = [[HMNavigationController alloc] initWithRootViewController:compose]; [self presentViewController:nav animated:YES completion:nil]; } 8、代理的设置整个步骤如上。 |
|
来自: 雪柳花明 > 《ios 开发项目遇到的问题》