簡體   English   中英

UIPicker單個組件可顯示多個陣列

[英]UIPicker single component to display multiple arrays

首先發表評論,所以我希望我做得對。

我正在和UIPicker打架。 我試圖在單個選擇器組件中顯示2列數據。 我之所以選擇在1個組件中執行此操作,是因為我希望數組一起滾動,而我無法讓多個組件一起執行。

麻煩的是,我也無法通過這種方式工作,因為titleForRow和viewForRow將僅返回一個值(按照C的規則)。 我試圖使它們輸出數組和字典,但這導致數據類型錯誤。 我可以使用1個組件,帶有viewForRow的1個數組來使其正常工作,但這僅允許對整個字段進行對齊,而不能對字符串的一部分進行對齊。

下面的代碼效果很好,並使用return label2給出了正確答案; 並且如果更改為return label1也正確,如何顯示兩者?

   - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *label1;
    {
        label1 = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 150.0f, 130.0f, 60.0f)];

        label1.textAlignment = NSTextAlignmentLeft;

        label1.text = [_firstList objectAtIndex:row];
    }

    UILabel *label2;
    {
    label2 = [[UILabel alloc] initWithFrame:CGRectMake(100.0f, 10.0f, 175.0f, 100.0f)];

      label2.textAlignment = NSTextAlignmentCenter;

        label2.text = [_secondList objectAtIndex:row];
    }
        return label2;
}

將您的UIPickerView設置為具有一個組件。

現在假設您的兩個數組_firstList_secondList具有相同數量的對象,則有兩個選擇:

  1. 使用簡單的pickerView:titleForRow:forComponent:方法從兩個值返回單個字符串構建:

     - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { return [NSString stringWithFormat:@"%@ - %@", _firstList[row], _secondList[row]]; } 

    當然,您可以根據需要設置兩個字符串的格式。 這是一個例子。

  2. 使用pickerView:viewForRow:forComponent:reusingView:就像您嘗試過的一樣,但是返回添加了兩個標簽的單個視圖。

     - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { UILabel *label1; UILabel *label2; if (view) { label1 = (UILabel *)[view viewWithTag:1]; label1 = (UILabel *)[view viewWithTag:2]; } else { view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)]; UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 0.0f, 130.0f, 40.0f)]; label1.tag = 1; label1.textAlignment = NSTextAlignmentLeft; UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(100.0f, 0.0f, 175.0f, 40.0f)]; label2.tag = 2; label2.textAlignment = NSTextAlignmentCenter; [view addSubview:label1]; [view addSubview:label2]; } label1.text = _firstList[row]; label2.text = _secondList[row]; return view; } 

    請注意這如何正確利用重用的視圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM