gpt4 book ai didi

ios - 更改 UIPickerView pickerView :viewForRow: attributes based on a certain condition

转载 作者:行者123 更新时间:2023-11-28 22:09:04 28 4
gpt4 key购买 nike

我正在尝试根据特定条件更改 viewForRow 中的文本颜色。当我按下按钮时, View 会更改为不同的颜色,但我也想更改选择器中文本的颜色。我使用“viewForRow”是因为我有自定义 View 。

//adds subcategories to the wheel
-(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.backgroundColor = [UIColor clearColor];


if (!self.isBackgroundWhite)//Boolean that changes when the background changes
{
NSLog(@"Set white text");
label.textColor = [UIColor whiteColor];

}else{

label.textColor = [UIColor blackColor];
}



if (row == 1) {
label.text = [NSString stringWithFormat:@" %@",[self.servicesArray objectAtIndex:row]];
label.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18];
}else{
label.text = [NSString stringWithFormat:@" -%@",[self.servicesArray objectAtIndex:row] ];
label.font = [UIFont fontWithName:kAppFont size:16];
}
return label;
}

编辑:感谢@Rich,我能够发现我的问题,我只需要调用[self.pickerView reloadAllComponents];

最佳答案

如果您只想更改文本颜色,只需使用其他委托(delegate)方法 pickerView:attributedTitleForRow:forComponent:

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

NSString *title;
UIFont *font;
if (row == 1) {
title = [NSString stringWithFormat:@" %@",[self.servicesArray objectAtIndex:row]];
font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18];
} else{
title = [NSString stringWithFormat:@" -%@",[self.servicesArray objectAtIndex:row] ];
font = [UIFont fontWithName:kAppFont size:16];
}

UIColor *textColor;
if (self.isBackgroundWhite) {
textColor = [UIColor blackColor];
} else {
NSLog(@"Set white text");
textColor = [UIColor whiteColor];
}

NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.alignment = NSTextAlignmentLeft;

NSDictionary *attributes = @{NSForegroundColorAttributeName : textColor,
NSFontAttributeName : font,
NSParagraphStyleAttributeName : paragraphStyle};

return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

另请注意,当更改 isBackgroundWhite 时,您应该调用 [self.pickerView reloadAllComponents];。我会通过重写 backgroundWhite 的 setter 并在 bool 值更改时重新加载选择器 View 来做到这一点。

编辑:
在 iOS 7(在 iOS 6 上工作正常)中似乎存在一个“错误”(有意或无意),在 返回的 NSAttributedString 上设置了 UIFont pickerView:attributedTitleForRow:forComponent: 方法。因此,虽然以上适用于文本颜色,但字体不会改变。幸运的是,您可以使用问题中的代码来解决这个问题。参见 this answer了解更多信息。

关于ios - 更改 UIPickerView pickerView :viewForRow: attributes based on a certain condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23289851/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com