如何将uipickerview作为子视图添加到iphone中的mainview?

时间:2011-05-26 09:56:44

标签: iphone uipickerview subview addsubview uipicker

我有一个应用程序,当用户点击一个按钮时,我想打开uipickerview作为主视图的子视图,在用户选择一个项目之后,它应该从主视图中删除。(下拉功能)。为此我编写如下代码:

-(void)showPrefPicker:(id)sender
{


   UIView *subView=[[UIView alloc] init];
   subView.frame=CGRectMake(180, 120, 150, 150);
   pickerView = [[UIPickerView alloc] init];

    pickerView.showsSelectionIndicator = YES;
    pickerView.dataSource = self;
    pickerView.delegate = self;
    pickerView.frame=CGRectMake(190, 130, 100, 100);
    subView.backgroundColor=[UIColor blackColor];
    [subView  addSubview:pickerView];
    [self.view addSubview:subView];
    [pickerView release];

}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    return 1;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSLog(@"selected object is %@",[arraypref objectAtIndex:row]);
    //[pickerView ]
    //mlabel.text=  [arrayNo objectAtIndex:row];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    return [arraypref count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
    return [arraypref objectAtIndex:row];
}

但是只在主视图中显示子视图而不是pickerview。我可以为此做任何教程或源代码吗?

3 个答案:

答案 0 :(得分:1)

更好的使用

隐藏

pickerview.hidden=YES;

显示

pickerview.hidden=NO;

答案 1 :(得分:0)

尝试将frame的{​​{1}}更改为

pickerView

答案 2 :(得分:0)

代码subView.frame=CGRectMake(180, 120, 150, 150);中的

pickerView.frame=CGRectMake(190, 130, 100, 100);

选择器视图是“子视图”

的子视图

这里pickerview的框架从子视图的边界开始,即原点x是190.但是子视图的宽度只有150.

所以正确的代码是

pickerView.frame=CGRectMake(0, 0, 100, 100);

因为pickerview是自定义视图的子视图。它应该在其父视图的框架中。