如何更改 UIPickerView 中选定行的颜色

发布于 2024-12-03 10:59:24 字数 2463 浏览 1 评论 0原文

好吧,也许我错过了一些非常简单的东西,如果是这样的话,我很抱歉,但是,我已经用谷歌搜索了标题的每个排列,但没有找到!所以这就是我想要做的:当选择该行时,更改我用作 2 组件选取器视图中的行视图的标签的背景颜色。所以我认为这会起作用:

if (row == [pickerview selectedRowForComponent])
    viewlabel.backgroundColor = redcolor;

但这行不通。它似乎任意选择对哪一行进行着色,有时甚至会给出错误的访问错误。我已经尝试了所有不同的条款,但没有效果!任何建议将不胜感激!

这是完整的方法:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{

    if (component == kNumberComponent) {


#define PICKER_LABEL_FONT_SIZE 24
#define PICKER_LABEL_ALPHA 1.0
        // UIFont *font = [UIFont boldSystemFontOfSize:PICKER_LABEL_FONT_SIZE];
        UIFont *font = [ UIFont fontWithName:@"AppleGothic"  size:24];
        UILabel *carsLabel =[ [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 75, 50) ]autorelease];
        //[picker selectRow:row inComponent:component animated:YES];
        NSString *pickerText = [self.numbers objectAtIndex:(int)row];
        carsLabel.text = pickerText;
        carsLabel.textAlignment = UITextAlignmentCenter;
        NSLog(@"carsLabel = %@",carsLabel.text);
        //carsLabel.text = @"maybe because the string isn't long enough";
        carsLabel.textColor = [UIColor blackColor];
        carsLabel.font = font;





        carsLabel.opaque = YES;


        [view addSubview:carsLabel];

        return carsLabel;   
    } else {
        UIFont *font = [ UIFont fontWithName:@"AppleGothic"  size:18];

        UILabel *carsLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 225, 50)] autorelease];
        id fact = [self.facts objectAtIndex:(int)row];
        NSString *pickerText = @"Dictionary Entry";
        if ( [fact isKindOfClass:[NSString class]]) {


            pickerText = [self.facts objectAtIndex:(int)row];

        } 
        carsLabel.text = pickerText;
        carsLabel.textAlignment = UITextAlignmentCenter;
        NSLog(@"carsLabel = %@",carsLabel.text);
        //carsLabel.text = @"maybe because the string isn't long enough";
        carsLabel.textColor = [UIColor blackColor];
        carsLabel.font = font;
        if ( row == 0) {
        carsLabel.backgroundColor = [UIColor redColor];

        }
        //carsLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blackboard.png"]];;
        carsLabel.opaque = YES;

        [view addSubview:carsLabel];

        return carsLabel;
    }


    return nil;
}

Ok, maybe I'm missing something really simple and I apologize if that's the case, however, I've googled every permutation of the title and have not found! So this is simply what I want to do: change the background color of the label I'm using as the row view in a 2 component pickerview when that row has been selected. So I thought this would work:

if (row == [pickerview selectedRowForComponent])
    viewlabel.backgroundColor = redcolor;

but this doesn't work. It seems to arbitrarily choose which row to color and sometimes even give a bad access error. I've tried all different clauses to no effect! ANy suggestions would be greatly appreciated!!

Here's the full method:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{

    if (component == kNumberComponent) {


#define PICKER_LABEL_FONT_SIZE 24
#define PICKER_LABEL_ALPHA 1.0
        // UIFont *font = [UIFont boldSystemFontOfSize:PICKER_LABEL_FONT_SIZE];
        UIFont *font = [ UIFont fontWithName:@"AppleGothic"  size:24];
        UILabel *carsLabel =[ [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 75, 50) ]autorelease];
        //[picker selectRow:row inComponent:component animated:YES];
        NSString *pickerText = [self.numbers objectAtIndex:(int)row];
        carsLabel.text = pickerText;
        carsLabel.textAlignment = UITextAlignmentCenter;
        NSLog(@"carsLabel = %@",carsLabel.text);
        //carsLabel.text = @"maybe because the string isn't long enough";
        carsLabel.textColor = [UIColor blackColor];
        carsLabel.font = font;





        carsLabel.opaque = YES;


        [view addSubview:carsLabel];

        return carsLabel;   
    } else {
        UIFont *font = [ UIFont fontWithName:@"AppleGothic"  size:18];

        UILabel *carsLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 225, 50)] autorelease];
        id fact = [self.facts objectAtIndex:(int)row];
        NSString *pickerText = @"Dictionary Entry";
        if ( [fact isKindOfClass:[NSString class]]) {


            pickerText = [self.facts objectAtIndex:(int)row];

        } 
        carsLabel.text = pickerText;
        carsLabel.textAlignment = UITextAlignmentCenter;
        NSLog(@"carsLabel = %@",carsLabel.text);
        //carsLabel.text = @"maybe because the string isn't long enough";
        carsLabel.textColor = [UIColor blackColor];
        carsLabel.font = font;
        if ( row == 0) {
        carsLabel.backgroundColor = [UIColor redColor];

        }
        //carsLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blackboard.png"]];;
        carsLabel.opaque = YES;

        [view addSubview:carsLabel];

        return carsLabel;
    }


    return nil;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

如果没结果 2024-12-10 10:59:24

通常,我使用这种方法:

我使用自定义视图来显示行项目,

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{

    UILabel *label = (id)view;

    if (!label)
    {

        label= [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor whiteColor];
        label.text = _arrayStringPicker[row];

    }  

    return label;

我更改所选行的颜色:

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

    UILabel *labelSelected = (UILabel*)[pickerView viewForRow:row forComponent:component];
    [labelSelected setTextColor:[UIColor redColor]];

}

Normally, I use this method:

I use the custom view for show the row item

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{

    UILabel *label = (id)view;

    if (!label)
    {

        label= [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor whiteColor];
        label.text = _arrayStringPicker[row];

    }  

    return label;

I change color of row selected with:

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

    UILabel *labelSelected = (UILabel*)[pickerView viewForRow:row forComponent:component];
    [labelSelected setTextColor:[UIColor redColor]];

}
失去的东西太少 2024-12-10 10:59:24

迅速实施

extension PickerViewController: UIPickerViewDelegate {
    func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        var color: UIColor!
        if pickerView.selectedRowInComponent(component) == row {
            color = UIColor.redColor()
        } else {
            color = UIColor.blackColor()
        }

        let attributes: [String: AnyObject] = [
            NSForegroundColorAttributeName: color,
            NSFontAttributeName: UIFont.systemFontOfSize(15)
        ]

        return NSAttributedString(string: rows[row], attributes: attributes)
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        //this will trigger attributedTitleForRow-method to be called
        pickerView.reloadAllComponents()
    }
}

Swift implementation

extension PickerViewController: UIPickerViewDelegate {
    func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        var color: UIColor!
        if pickerView.selectedRowInComponent(component) == row {
            color = UIColor.redColor()
        } else {
            color = UIColor.blackColor()
        }

        let attributes: [String: AnyObject] = [
            NSForegroundColorAttributeName: color,
            NSFontAttributeName: UIFont.systemFontOfSize(15)
        ]

        return NSAttributedString(string: rows[row], attributes: attributes)
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        //this will trigger attributedTitleForRow-method to be called
        pickerView.reloadAllComponents()
    }
}
薄情伤 2024-12-10 10:59:24

viewForPicker 的正确格式是:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *label = (UILabel*) view;
    if (label == nil)
    {
        label = [[UILabel alloc] init];
    }

    [label setText:@"Whatever"];

    // This part just colorizes everything, since you asked about that.

    [label setTextColor:[UIColor whiteColor]];
    [label setBackgroundColor:[UIColor blackColor]];
    CGSize rowSize = [pickerView rowSizeForComponent:component];
    CGRect labelRect = CGRectMake (0, 0, rowSize.width, rowSize.height);
    [label setFrame:labelRect];

    return label;
}

上面代码的问题是:它为标签着色,而不是选择器本身。因此,当您滚动到一端或另一端时,会出现一个空白点,您可以在其中看到白色背景。设置 [myPicker setBackgroundColor...] 并不能达到人们所希望的效果。

The correct format for viewForPicker is:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *label = (UILabel*) view;
    if (label == nil)
    {
        label = [[UILabel alloc] init];
    }

    [label setText:@"Whatever"];

    // This part just colorizes everything, since you asked about that.

    [label setTextColor:[UIColor whiteColor]];
    [label setBackgroundColor:[UIColor blackColor]];
    CGSize rowSize = [pickerView rowSizeForComponent:component];
    CGRect labelRect = CGRectMake (0, 0, rowSize.width, rowSize.height);
    [label setFrame:labelRect];

    return label;
}

The problem with the code above is: it colorizes the labels, but not the picker, itself. So, when you roll to one end or the other, there's a blank spot where you can see the white background. Setting [myPicker setBackgroundColor...] doesn't do what one might hope.

時窥 2024-12-10 10:59:24

解决了!声明 2 个实例变量:selectedView 和 oldView。然后下面的代码就可以解决问题:

if (self.oldView != nil)
        self.oldView.backgroundColor = [UIColor clearColor];

self.selectedView = [picker viewForRow:row forComponent:kNumberComponent];
        self.selectedView.backgroundColor = [UIColor redColor];
        [self.selectedView setNeedsDisplay];
        self.oldView = self.selectedView;

Solved! Declare 2 instance variables: selectedView, and oldView. Then the following code does the trick:

if (self.oldView != nil)
        self.oldView.backgroundColor = [UIColor clearColor];

self.selectedView = [picker viewForRow:row forComponent:kNumberComponent];
        self.selectedView.backgroundColor = [UIColor redColor];
        [self.selectedView setNeedsDisplay];
        self.oldView = self.selectedView;
拥醉 2024-12-10 10:59:24

@alessandro-pirovano 答案的 Swift 版本

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

    let rowSize = pickerView.rowSize(forComponent: component)
    let width = rowSize.width
    let height = rowSize.height
    let frame = CGRect(x: 0, y: 0, width: width, height: height)
    let label = UILabel(frame: frame)
    label.textAlignment = .center
    label.text = rows[row]

    return label
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    guard let label = pickerView.view(forRow: row, forComponent: component) as? UILabel else {
        return
    }
    label.backgroundColor = .orange
}

Swift version of @alessandro-pirovano answer

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

    let rowSize = pickerView.rowSize(forComponent: component)
    let width = rowSize.width
    let height = rowSize.height
    let frame = CGRect(x: 0, y: 0, width: width, height: height)
    let label = UILabel(frame: frame)
    label.textAlignment = .center
    label.text = rows[row]

    return label
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    guard let label = pickerView.view(forRow: row, forComponent: component) as? UILabel else {
        return
    }
    label.backgroundColor = .orange
}
嘿看小鸭子会跑 2024-12-10 10:59:24

// CGRect为我们想要的框架创建值

UIPickerView *myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0,0, self.view.bounds.size.width, self.view.bounds.size.height)];

// add the UIPickerView to your viewcontroller [mainView addSubview:myPickerView];

// set the selectionindicator to none myPickerView.showsSelectionIndicator = NO;

// 定义我们想要使用的图像

UIImage *selectorImage = [UIImage imageNamed:@"selectionIndicator.png"];

UIView *customSelector = [[UIImageView alloc] initWithImage:selectorImage];

// 将 x 和 y 值设置为 UIPickerView 上要放置图像的点

// 设置宽度和高度图像的宽度和高度的值

customSelector.frame = CGRectMake(10,(myPickerView.bounds.size.height / 2) + 16, self.view.bounds.size.width – 10, 47);

// 将自定义选择指示器也添加到同一个视图控制器

[mainView addSubview:customSelector];

// CGRectMake values for the frame we’d like

UIPickerView *myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0,0, self.view.bounds.size.width, self.view.bounds.size.height)];

// add the UIPickerView to your viewcontroller [mainView addSubview:myPickerView];

// set the selectionindicator to none myPickerView.showsSelectionIndicator = NO;

// define the image that we would like to use

UIImage *selectorImage = [UIImage imageNamed:@"selectionIndicator.png"];

UIView *customSelector = [[UIImageView alloc] initWithImage:selectorImage];

// set the x and y values to the point on the UIPickerView where you want to place the image

// set the width and height values to the width and height of your image

customSelector.frame = CGRectMake(10,(myPickerView.bounds.size.height / 2) + 16, self.view.bounds.size.width – 10, 47);

// add the custom selectionIndicator also to the same viewcontroller

[mainView addSubview:customSelector];
来世叙缘 2024-12-10 10:59:24

调用 UIPickerView 实例的 -viewForRow:forComponent: 方法来获取 UIView * 对象。然后设置该视图的背景UIColor

Call the UIPickerView instance's -viewForRow:forComponent: method to get the UIView * object. Then set that view's background UIColor.

本王不退位尔等都是臣 2024-12-10 10:59:24

目前尚不清楚您将上述代码放在哪里。是在 -pickerView:viewForRow:forComponent:reusingView: 中吗?这是它应该在的地方。您确定正在维护指向该特定视图的标签的指针吗?您崩溃的事实表明您可能没有崩溃。更大的代码块(包括您放置它的位置)会很有帮助。

It's unclear where you are putting the above code. Is it in -pickerView:viewForRow:forComponent:reusingView:? This is where it should be. Are you sure that you are maintaining a pointer to the label for that particular view? The fact that you are crashing suggests you probably are not. A larger block of code, including where you have put it, would be helpful.

沧笙踏歌 2024-12-10 10:59:24

这对我有用:

  1. UIView 作为子视图添加到您的 UIPickerView 中,
  2. 将其限制为使用您的 UIPickerView 输入 Y,并且具有相同的内容width
  3. 给它的高度等于 pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> > 返回的高度CGFloat
  4. 使其半透明并按照您想要的方式着色

*其余解决方案(使用行的自定义视图或行的属性字符串)在快速滚动时会出现错误。

Here's what worked for me:

  1. Add a UIView as a subview to your UIPickerView
  2. Constrain it to be Y entered with your UIPickerView and the has the same width
  3. Give it height equal to the height of what returned in pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat
  4. Make it semi transparent and color it the way you want

*the rest of the solutions (with custom views for row or attributed stringsfor row) were buggy when scrolling fast.

画离情绘悲伤 2024-12-10 10:59:24

UIPickerView 有委托为行和组件的标题设置 NSAttributeString 我们可以设置属性颜色,如下所示:

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSDictionary *attrs = @{NSForegroundColorAttributeName : [UIColor redColor]};
    NSString *title = @"title"
    return [[NSAttributedString alloc] initWithString:title attributes:attrs];

}

UIPickerView has delegate to set NSAttributeString for title at row and component we can set attribute color like below:

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSDictionary *attrs = @{NSForegroundColorAttributeName : [UIColor redColor]};
    NSString *title = @"title"
    return [[NSAttributedString alloc] initWithString:title attributes:attrs];

}

硪扪都還晓 2024-12-10 10:59:24

扩展 Alessandro Pirovano 的答案;

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

    UILabel *labelSelected = (UILabel*)[pickerView viewForRow:row forComponent:component];
    [labelSelected setTextColor:[UIColor redColor]];
    labelSelected.superview.backgroundColor = [UIColor yellowColor];
}

Expanding on Alessandro Pirovano's answer;

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

    UILabel *labelSelected = (UILabel*)[pickerView viewForRow:row forComponent:component];
    [labelSelected setTextColor:[UIColor redColor]];
    labelSelected.superview.backgroundColor = [UIColor yellowColor];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文