1.下面代码是描述: 点击Toolbar上的按钮时,通知代理去调代理方法.
1 - (void)didClickedToolbarBtn:(UIButton *)button 2 { 3 4 if ([self.delegate respondsToSelector:@selector(toolbar:didClickedButton:)]) { 5 [self.delegate toolbar:self didClickedButton:button.tag]; 6 } 7 self.selectButton.selected = NO; 8 button.selected = YES; 9 self.selectButton = button; 10 11 }
2.不巧的是,此时delegate还没指定,也就是说delegate=nil,具体场景如下:
1>假设有个控制器,在控制器的viewDidLoad方法里实例化Toolbar,也就是调[ [ Toolbar alloc ] init ].在执行完init后才是 toolbar.delegate = self.
2>在Toolbar的init方法添加Toolbar的4个按钮,[self addToolbarButtonWithTitle:@"xxx" andTag:枚举类型].
3>要求默认点击第1个按钮,采用的方法是,在创建按钮时,校验toolbar.subview的数量,当数量为1时,执行 [self didClickedToolbarBtn:button]
1 - (void)addToolbarButtonWithTitle:(NSString *)title andTag:(QKToolbarButtonType)toolbarButtonType 2 { 3 QKToolbarButton *button = [[QKToolbarButton alloc]init]; 4 button.tag = toolbarButtonType; 5 6 [button setTitle:title forState:UIControlStateNormal]; 7 8 [button addTarget:self action:@selector(didClickedToolbarBtn:) forControlEvents:UIControlEventTouchDown]; 9 10 [self addSubview:button]; 11 12 if (self.subviews.count == 1) { 13 [self didClickedToolbarBtn:button]; 14 } 15 }
3.为了结局上文描述的delegate=nil的问题,可以采用下面的解决办法,在代理的set方法中调相应的方法
1 - (void)setDelegate:(id<QKToolbarDelegate>)delegate 2 { 3 _delegate = delegate; 4 QKToolbarButton *toolbarBtn = (QKToolbarButton *)[self viewWithTag:QKToolbarButtonTypeDefault]; 5 [self didClickedToolbarBtn:toolbarBtn]; 6 7 }