iOS中UIPickerview的应用和去掉边线

1,905 阅读1分钟

1:uipickerview的使用 2:返回一个富文本的显示 3:设置cell的行高 4:设置返回一个自定义的view 5:设置pickerview的上下两条线的颜色或者隐藏掉

picker view的实例化

    self.pickView = [[UIPickerView alloc] init];
    self.pickView.dataSource = self;
    self.pickView.delegate = self;
    self.pickView.userInteractionEnabled = NO;
    [self.backGroundView addSubview:self.pickView];
    self.pickView.showsSelectionIndicator = NO;

设置self.pickView.userInteractionEnabled = NO; 就是让用户不能点击有翻滚的效果

使用几个必须的使用函数

   #pragma mark - uipickview DELEGATE
   -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
   }

  -(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.dataArry.count;
   }

2.1 返回一个富文本编辑效果

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSString * reStr = self.dataArry[row];
    // 创建一个富文本
    NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:reStr];
    // 修改富文本中的不同文字的样式
    [attriStr addAttribute:NSForegroundColorAttributeName value:YSColor(88, 164, 240) range:NSMakeRange(0, reStr.length)];
    //[attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, reStr.length)];
    ((UIView *)[self.pickView.subviews objectAtIndex:1]).backgroundColor = [YSColor(255, 255, 255) colorWithAlphaComponent:0.5];
    return attriStr;
}

2.2 设置cell的行高

-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 20;
}

2.3 设置cell为custom的view

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    CGFloat width = 125.0f;
    CGFloat height = 20.0f;
    
    UIView * myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    myView.backgroundColor = [UIColor clearColor];
    
    UILabel * complateLabel = [[UILabel alloc] init];
    complateLabel.center = myView.center;
    complateLabel.bounds = CGRectMake(0, 0, width, height);
    complateLabel.textColor = YSColor(88, 164, 240);
    complateLabel.textAlignment = NSTextAlignmentCenter;
    complateLabel.font = FONTWITHSIZE_LIGHT(14);
    complateLabel.text =  self.dataArry[row];
    [myView addSubview:complateLabel];
    
    ((UIView *)[self.pickView.subviews objectAtIndex:1]).backgroundColor = [YSColor(255, 255, 255) colorWithAlphaComponent:0.5];
    if (IS_IOS7) {
        ((UIView *)[self.pickView.subviews objectAtIndex:2]).backgroundColor = [YSColor(255, 255, 255) colorWithAlphaComponent:0.5];
    }
    return myView;
}

这里的

((UIView *)[self.pickView.subviews objectAtIndex:1]).backgroundColor = [YSColor(255, 255, 255) colorWithAlphaComponent:0.5];

((UIView *)[self.pickView.subviews objectAtIndex:2]).backgroundColor = [YSColor(255, 255, 255) colorWithAlphaComponent:0.5];

是设置pickview的上下两条线的颜色,或者隐藏他