我希望在自定义文本后填充我的选择器视图。当我可以用数组填充它时,我无法更改它的文本颜色。我到处搜索,我发现它们都是分开的,或者它们已经改变了文本颜色,或者用数组填充它。以下是我试过的代码。
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [self.CityList count];
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width, 44)];
label.textColor = [UIColor whiteColor];
label.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18];
label.textAlignment = NSTextAlignmentCenter;
if (row == 0)
{
label.text = self.CityList[0];
}
else if (row == 1)
{
label.text = self.CityList[1];
}
else if (row == 2)
{
label.text = self.CityList[2];
}
else if (row == 3)
{
label.text = self.CityList[3];
}
else if (row == 4)
{
label.text = self.CityList[4];
}
else if (row == 5)
{
label.text = self.CityList[5];
}
return label;
}
这段代码实际上运行正常但是当我的数组中有太多代码时,以这种方式实现它绝对没有效率。请建议我一个有效的方法。
答案 0 :(得分:2)
像这样改变你的方法:
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
UILabel *label = (UILabel *)view;
//Check if the current view requested is a reused one, If not then create a new one
if (!label)
{
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width, 44)];
}
label.textColor = [UIColor whiteColor];
label.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18];
label.textAlignment = NSTextAlignmentCenter;
//Assign the text of the label to the NSString at the index of "row" from your data array
label.text = self.CityList[row];
return label;
}
答案 1 :(得分:0)
我刚修好它,我发现我出错的地方无法直接使用数组进行分配。我已将我的数组属性分配给弱。在我把它改成强大的......后,它工作正常......;)