我使用的是自定义UIPickerView
:
-(UIView *)pickerView:(UIPickerView *)pickerView
viewForRow:(NSInteger)row
forComponent:(NSInteger)component
reusingView:(UIView *)view
使用UILabels
填充选择器。有没有办法在触摸时禁用突出显示所选行的行为?
我认为这是UITableViewCell
中固有的基础UIPickerView
的属性,我无法找到改变它的方法。
答案 0 :(得分:16)
您需要确保自定义视图具有以下属性:
pickerView:rowHeightForComponent:
和pickerView:widthForComponent:
,其大小必须与UIPickerView所需的尺寸相同。如果您未指定自定义高度,则默认高度为44。[UIColor clearColor]
。使用UILabel
个实例作为自定义视图的问题是UILabel
默认userInteractionEnabled
到NO
(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;
}
答案 1 :(得分:12)
将userInteractionEnabled
的{{1}}属性设置为UILabel
可修复突出显示问题,但它也会禁用YES
自动滚动以选择已触摸的行。
如果要禁用突出显示行为,但保留UIPickerView
的默认自动滚动功能,请调用UIPickerView
中包含的setShowSelection
个实例中的UITableCell
函数。这样做的一种方法是将UIPickerView
类子类化为类似于以下内容:
PickerViewLabel.h -
UILabel
PickerViewLabel.m -
#import <UIKit/UIKit.h>
@interface PickerViewLabel:UILabel
{
}
@end
然后,您之前在#import "PickerViewLabel.h"
@implementation PickerViewLabel
- (void)didMoveToSuperview
{
if ([[self superview] respondsToSelector:@selector(setShowSelection:)])
{
[[self superview] performSelector:@selector(setShowSelection:) withObject:NO];
}
}
@end
中返回UILabel
的实例的位置,返回pickerView:viewForRow:forComponent:reusingView:
的实例。例如,使用Doug中的代码,您可以将“PickerViewLabel
”的所有情况替换为“UILabel
”。请记住删除PickerViewLabel
行。
答案 2 :(得分:0)
我想你可能想看一下UIPickerView的“showsSelectionIndicator”属性
答案 3 :(得分:0)
我不确定是否有一种简单的方法可以删除选择反馈,但是如果您将标签的背景设置为白色并将其尺寸调整为与蓝色选择矩形相同的尺寸,则可以将其覆盖:
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
UILabel *pickerRowLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 316, 40)];
pickerRowLabel.backgroundColor = [UIColor whiteColor];
pickerRowLabel.text = [pickerDataArray objectAtIndex:row];
[self.view addSubview:pickerRowLabel];
return pickerRowLabel;
}
宽度为316时,标签覆盖除了每侧的蓝色条纹以外的所有条纹,并且在320处它完全覆盖选择反馈,但它也开始覆盖一些外轮渐变,这可能会或可能不会打扰你。