UIPickerView的大小设置不正确

| 我需要显示一个不是全屏的视图,并且下面有一个按钮和pickerView。 我尝试使用此代码:
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(20,20,200,200)];
        container.backgroundColor=[UIColor whiteColor];

        UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        myButton.frame = CGRectMake(container.frame.origin.x, container.frame.origin.y+5, 170, 20); // position in the parent view and set the size of the button
        myButton.titleLabel.textColor=[UIColor redColor];
        myButton.titleLabel.text=@\"click me\";
        //myButton.backgroundColor=[UIColor blueColor];
        //[myButton backgroundImageForState:<#(UIControlState)#>[UIImage imageNamed:@\"iPhone_mainbutton_green.png\"];
        // add targets and actions
        [myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        // add a buttonview
        [container addSubview:myButton];

        UIPickerView *piker=[[UIPickerView alloc] initWithFrame:CGRectMake(container.frame.origin.x, container.frame.origin.y +30, 100, 100)];
        //piker.numberOfComponents=1;
        piker.showsSelectionIndicator=YES;
        //piker.delegate=self;
        //piker.dataSource=self;

        [container addSubview:piker];

        [myButton release];
        [piker release];

        [self.view addSubview:container];
我得到这个(选择器在屏幕外,非常大,而不是100x100):     
已邀请:
        您正在容器中添加选择器视图,并且容器框架为:-( 20,20,200,200) 做成
(0,20,200,200)
。     
        您正在将UIPickerView添加为\“ container \”的子视图
UIPickerView *piker=[[UIPickerView alloc] initWithFrame:CGRectMake(container.frame.origin.x, container.frame.origin.y +30, 100, 100)];
这意味着pickerview从容器而不是从UIView获取其起源,如果您希望它位于正确的位置,请执行以下操作:
UIPickerView *piker=[[UIPickerView alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 100)];
[container addSubview:picker];
仅关注您的原点,并记住每个子视图都从其父视图获取其原点。 苹果还有另一件事不允许更改pickerview高度,因此您不能将其设置为100x100,只能更改其宽度。 UIPickerView仅支持3个高度值,分别是216.0,180.0和162.0尝试仅从这3个值设置高度。这将是工作。 让我知道您是否对此有任何疑问。     
        如果要调整框架,请使用视图控制器的
viewWillAppear:
方法进行调整-您可以在那里进行调整。 确保您还实现了
widthForComponent:
,并且所有组件的宽度都小于帧宽度-拾取器插入。我使用以下内容:
- (void)viewDidLoad{
    self.picker = [[[UIPickerView alloc] init] autorelease];
    [self.view addSubview:self.picker];  
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.settingsPicker.frame =  CGRectMake(0.0, 100.0, self.view.frame.size.width, 100.0);
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    CGFloat guessedPickerInsetWidth = 24;
    CGFloat pickerWidth = self.view.frame.size.width - guessedPickerInsetWidth;
    if (component == SettingsPickerFirstComponent) {
        return pickerWidth * 0.4; // make the first component 40%
    }
    return pickerWidth * 0.3; // only two others, make them 30% each
}
    

要回复问题请先登录注册