如何填充自定义单元格的 UIPickerView

How do I populate Custom Cell's UIPickerView

我想填充 UICollectionView 的单元格。 我创建了一个自定义单元格,它由一个 Label 和 TextFiled 组成,我已经以编程方式将其 inputView 更改为 UIPickerView,因此它的行为类似于 pickerview,我的问题是我有自定义单元格 .h 和 .m 文件并且我有一个控制器 class,collectionview 工作正常,但我无法将数据添加到 UIPickerview,因为它在 indvidual .h 文件中,所以它是 pickerview 委托,数据源方法将在它的 .m 文件中。

但我的数据在主 VC class 如何从 VC 填充选择器视图?

我是 objective c 的新手,很抱歉,如果没有清楚地解释我的问题

我已经尝试在我的 VC class 中获取单元格并在 VC class 中填充单元格的 pickerview 但这行不通,因为我无法访问单元格的外部字段 - (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{} 方法。

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


    - (NSInteger)pickerView:(nonnull UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if(pickerView.tag==0){
        return outboundBaggages.count;
    }
    return 0;
}


    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if(pickerView.tag==0){
        NSString *key = [NSString stringWithFormat:@"%ld",(long)row];
        ssrDescription = listOfOutboundSSR[key];
        //cell.ssrTextField.text = listOfOutboundSSR[key];
       //above line should be the right but it is field of cell and i 
       //can not access it outside of collectionview's method 
    }
}


    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if(pickerView.tag==0){
         NSString *key = [NSString stringWithFormat:@"%ld",(long)row];
        return listOfOutboundSSR[key];
    }
    return nil;
}

您需要在控制器中创建一个 属性,即 selectedCell with DataType 作为您的自定义单元格 class 类型。

在UICollectionView的下面的数据源中,符合UITextfieldDelegate

(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

///....
cell.textfield.delegate = self; 
}

现在实现textfield的delegate方法并赋值给selectedCell

- (void)textFieldDidBeginEditing:(UITextField *)textField {

   CGPoint tfPosition = [textField convertPoint:CGPointZero toView:self.collectionView];
   NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:tfPosition];
   selectedCell = [self.collectionView cellForItemAtIndexPath: indexPath];
}

现在,您可以在 UIPIckerView 数据源、委托方法中使用 selectedCell //selectedCell.ssrTextField.text = listOfOutboundSSR[key];