(iOS) How to make first value in UIPickerView unse

2019-08-31 09:08发布

I'm using UIPickerView with (for example) 4 rows. The first value is "Pick a value" with gray text. The others are values the user should pick with black text.

The picking is optional, so users could just skip it. But if they don't, how to make first value unselectable back after user will start picking?

Thanks. Regards.

1条回答
Lonely孤独者°
2楼-- · 2019-08-31 09:42

Use the UIPickerView delegate method - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component to change the selected row if the first row is selected :

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    if (row == 0) {
        [pickerView selectRow:row+1 inComponent:component animated:YES];
    }
}

Edit : you may be able to change the text color using this :

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component {

    if (row == 0)
        return [[NSAttributedString alloc] initWithString:@"Pick a value" attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor]}];
    else {
        // Return titles
    }
}

This is if you target iOS 6+, and it replaces the previously used -pickerView:titleForRow:forComponent: method.

查看更多
登录 后发表回答