iOS开发ios原理iOS

iOS 自定义弹框+picker view+delegate

2015-07-24  本文已影响1735人  泥_叔

根据需求文档,要实现一个弹框选择器,本来想在网上找一个人家写好的拿来用用的,但是最近收到多方打击,决定动手写一个。虽然很简单,但是最起码是自己的东西,同时呢,也希望能给其他人带来一丁点的用处。

需求说明:

1.点击选择按钮时,弹出选择框,选择之后显示选择的内容。
2.iOS要求使用拾取器来实现。··
简单的效果图如下:


IMG_1175.PNG

界面没什么好说的,我就来说说里面的代理吧。代理在开发过程中用到的很多的,也是一个很少用的设计模式。

首先要在pickViewController.h文件中声明一个协议;

@protocol pickViewDelegate <NSObject>
- (void) getTextStr:(NSString *)text;
@end
@property (nonatomic, unsafe_unretained) id<pickViewDelegate> delegate;//声明代理

pickViewController.m中点击事件

//确定按钮
- (IBAction)submit:(id)sender{
if (_delegate && [_delegate respondsToSelector:@selector(getTextStr:)])     {
    [_delegate getTextStr:_chooseText];
}
[self dismissViewControllerAnimated:YES completion:nil];
}

在viewcontrol.h页面中实现代理

@interface ViewController : UIViewController<pickViewDelegate>
@property (nonatomic, weak) IBOutlet UILabel *showTextLb;

在viewcontrol.m页面中接受代理传过来的值

<pre><code>- (void)getTextStr:(NSString *)text{
_showTextLb.text = text;
}
</code></pre>

需要注意的是viewcontrol.m中的页面跳转这段代码

  pickViewController *pick = [[pickViewController alloc] initWithNibName:@"pickViewController" bundle:nil];
  pick.delegate = self;//此处一定要实现自己的代理
  pick.modalPresentationStyle = UIModalPresentationCustom;
  [self presentViewController:pick animated:YES completion:nil];
代码下载地址:

http://www.cocoachina.com/bbs/read.php?tid=314926

上一篇 下一篇

猜你喜欢

热点阅读