覆盖UIPickerView中突出显示的选择

Jon*_*Jon 8 iphone cocoa-touch uipickerview

我有一个UIPickerView我使用的自定义:

-(UIView *)pickerView:(UIPickerView *)pickerView
       viewForRow:(NSInteger)row
     forComponent:(NSInteger)component 
      reusingView:(UIView *)view
Run Code Online (Sandbox Code Playgroud)

填充选择器UILabels.有没有办法在触摸时禁用突出显示所选行的行为?

我认为这是UITableViewCell固有的潜在属性,UIPickerView我无法找到改变它的方法.

Dou*_*rth 16

您需要确保自定义视图具有以下属性:

  1. 它的大小必须与UIPickerView根据您的委托方法所期望的尺寸相同 - pickerView:rowHeightForComponent:并且pickerView:widthForComponent:.如果未指定自定义高度,则默认高度为44.
  2. 背景颜色必须是[UIColor clearColor].
  3. 视图必须捕获所有触摸.

使用UILabel实例作为自定义视图时的问题是UILabel默认userInteractionEnabledNO(UIView另一方面,默认为此属性YES).

根据这些要求,Halle的示例代码可以重写如下.此示例还正确地重用了以前创建的视图,这是快速滚动性能所需的.

- (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;
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ine 12

设置userInteractionEnabled属性UILabelYES修复突出显示问题,但它还会禁用UIPickerView自动滚动以选择已触摸的行.

如果要禁用突出显示行为,但保持UIPickerView默认的自动滚动功能,请在包含setShowSelectionUITableCell实例中调用该函数UIPickerView.这样做的一种方法是将类子UILabel类化为类似于以下内容:

PickerViewLabel.h -

#import <UIKit/UIKit.h>

@interface PickerViewLabel:UILabel 
{
}

@end
Run Code Online (Sandbox Code Playgroud)

PickerViewLabel.m -

#import "PickerViewLabel.h"

@implementation PickerViewLabel

- (void)didMoveToSuperview
{
 if ([[self superview] respondsToSelector:@selector(setShowSelection:)])
 {
  [[self superview] performSelector:@selector(setShowSelection:) withObject:NO];
 }
}

@end
Run Code Online (Sandbox Code Playgroud)

然后,在您之前返回UILabelin 的实例的位置pickerView:viewForRow:forComponent:reusingView:,返回一个实例PickerViewLabel.例如,使用Doug的代码,您将替换' UILabel'with' PickerViewLabel'的所有情况.只记得删除该pickerRowLabel.userInteractionEnabled = YES;行.