【问题标题】:ios drop down menu on button click点击按钮时的ios下拉菜单
【发布时间】:2014-09-12 11:10:14
【问题描述】:

我发现以下site 的代码应该显示一个按钮,一旦单击,它就会显示一个下拉菜单。未显示任何按钮,因此无法测试功能。

我错过了什么吗?我必须在 UI 中创建一个元素并链接它吗?

这是我的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.countriesArray = [[NSArray alloc] initWithObjects:@"Saudi Arabia", @"United Arab Emirates", @"Bahrain", nil];
    self.countriesPicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
    [self attachPickerToTextField:self.countriesTextfield :self.countriesPicker];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)attachPickerToTextField: (UITextField*) textField :(UIPickerView*) picker{
    picker.delegate = self;
    picker.dataSource = self;
    textField.delegate = self;
    textField.inputView = picker;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.countriesTextfield resignFirstResponder];
}

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


- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView == self.countriesPicker){
        return self.countriesArray.count;
    }
        return 0;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView == self.countriesPicker){
        return [self.countriesArray objectAtIndex:row];
    }

    return @"???";
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (pickerView == self.countriesPicker){
        self.countriesTextfield.text = [self.countriesArray objectAtIndex:row];
    }
}

【问题讨论】:

  • 这个视图有 UIPickerView 委托方法,但它是否正确连接到情节提要中?如果没有,则不会捕获任何用于设置选择器视图的委托方法。按钮没有任何意义——只是从硬编码的选项数组中创建一个加载了国家名称的pickerView。选择拾取器行时,它将该国家名称放入TextField中。它设置textField.inputView = picker 的行应该是设置选择器而不是键盘显示的位置。在textView中点击是不是没有出现?

标签: ios


【解决方案1】:

您发布的链接只是一个下载页面,其中包含 NSViewController 子类的代码,因此我没有上下文可以给出全面的答案。此外,链接代码与问题中引用的代码不匹配(这必须是简化版本?),所以我下面的答案是指链接代码,我至少可以看到其中实例化 IBOutlet 属性的位置。

此代码将两个 UIPickerView 连接到两个 UITextField。没有按钮,也没有下拉菜单。从链接上的代码看来,选择器和文本字段已在 Interface Builder 中设置和连接。我这样说是因为 IBOutlet 属性是在代码内部设置的,它们没有暴露在头文件的外部接口中。

但是,为了使这按预期工作,以便 UIPickerViews 在加载时不可见,我认为有必要在代码中实例化它们。看到这个答案:instantiating UIPickerView for UITextField

【讨论】:

  • 你在哪里看到 2?只有国家选择器和国家文本字段。
  • 感谢您指出这一点。将编辑修复。我给出的答案是基于链接的文件,它似乎与引用的代码不匹配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多