Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

iphone - Overriding highlighted selection in UIPickerView

I have a custom UIPickerView where I use:

-(UIView *)pickerView:(UIPickerView *)pickerView
       viewForRow:(NSInteger)row
     forComponent:(NSInteger)component 
      reusingView:(UIView *)view

to populate the picker with UILabels. Is there a way to disable the behavior of highlighting the selected row when touched?

I think this is a property of the underlying UITableViewCell inherent in the UIPickerView and I can't find a way to change it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to make sure your custom view has the following properties:

  1. It needs to be sized to the same dimensions that the UIPickerView expects based on your delegate methods -- pickerView:rowHeightForComponent: and pickerView:widthForComponent:. The default height is 44 if you're not specifying a custom height.
  2. The background color must be [UIColor clearColor].
  3. The view must capture all touches.

The one gotcha when using UILabel instances as the custom view is that UILabel defaults userInteractionEnabled to NO (UIView, on the other hand, defaults this property to YES).

Based on these requirements, the example code from Halle can be rewritten as follows. This example also correctly reuses previously created views, which is needed for fast scrolling performance.

- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component
           reusingView:(UIView *)view {

  UILabel *pickerRowLabel = (UILabel *)view;
  if (pickerRowLabel == nil) {
    // Rule 1: width and height match what the picker view expects.
    //         Change as needed.
    CGRect frame = CGRectMake(0.0, 0.0, 320, 44);
    pickerRowLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
    // Rule 2: background color is clear. The view is positioned over
    //         the UIPickerView chrome.
    pickerRowLabel.backgroundColor = [UIColor clearColor];
    // Rule 3: view must capture all touches otherwise the cell will highlight,
    //         because the picker view uses a UITableView in its implementation.
    pickerRowLabel.userInteractionEnabled = YES;
  }
  pickerRowLabel.text = [pickerDataArray objectAtIndex:row];  

  return pickerRowLabel;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...