设置:
将PickerView(spinSelector)和标签(chosenItem)添加到ViewController中。 为PickerView委托创建单独的委托类文件(SpinDelegate m& h)。 创建委托的实例(SpinDelegate * mySpinDelegate) 将委托属性分配给委托实例
ViewController.h
@interface ViewController : UIViewController
{
SpinDelegate *mySpinDelegate;
}
@property (nonatomic, weak) IBOutlet UILabel *chosenItem;
@property (nonatomic, strong) IBOutlet UIPickerView *spinSelector;
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
mySpinDelegate=[[SpinDelegate alloc]init];
self.spinSelector.delegate=mySpinDelegate;
self.spinSelector.dataSource=mySpinDelegate;
}
SpinDelegate.h
@interface SpinDelegate : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>
{
ChoiceData *choiceItems;
}
@end
SpinDelegate.m
#pragma mark - PickerView Delegate
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component{
return [choiceItems.choiceList objectAtIndex:row];
}
接下来是使用方法:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component;
这是UIPickerViewDelegate
协议的一部分。使用此方法,只需将ViewController
中的UILabel(selectedItem)更改为行的值即可。类似于&#34;挑选的项目是%i&#34;,行
我已经通过大量关于UIViewController
到UIViewController
消息的帖子和问题进行了阅读和搜索,并查看了协议/代表,单身人士,NSNotificationCenter
...它只是在我看来,我缺少一个语法来解决父/超? ViewController
创建了委托的实例,委托没有范围吗?
请教育我这个。 :)
答案 0 :(得分:1)
您可以这样做:
<强> ViewController.h 强>
#import "SpinViewController.h"
@interface ViewController : UIViewController<SpinViewControllerDelegate>
{
}
@property (nonatomic, weak) IBOutlet UILabel *chosenItem;
@property (nonatomic, strong) IBOutlet UIPickerView *spinSelector;
<强> ViewController.m 强>
- (void)someFunction
{
mySpinViewController=[[SpinViewController alloc]init];
mySpinViewController.delegate=self;
// show or present mySpinViewController
}
//implement the followed protocol's method
-(void) optionSelected:(NSString*)cellValue{
}
<强> SpinViewController.h 强>
@protocol SpinViewControllerDelegate <NSObject>
@optional
-(void) optionSelected:(NSString*)cellValue;
@end
@interface SpinViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>
{
ChoiceData *choiceItems;
}
@property (nonatomic,retain)id <SpinViewControllerDelegate> delegate;
@end
<强> SpinViewController.m 强>
-(void) pickerValueSelectedOrSimilarFn:(NSString*)cellValue{
// this is how you give a callback to classes following the protocol
[self.delegate optionSelected:cellValue];
}