如何从颜色选择器方法设置按钮的颜色?

时间:2013-11-23 14:54:27

标签: ios iphone objective-c ipad ios7

我在for循环中生成一些按钮,每个按钮都有自己的标记。现在我想点击一个按钮并打开颜色选择器并设置按钮的颜色。

我的问题是,当我打开颜色选择器并选择一种颜色时,它会被设置在另一个按钮上。我想点击一个按钮,只选择点击按钮的颜色。

我使用的代码是:

for(int i=0;i<=5;i++){ 
    btnphoto=[[UIButton alloc]initWithFrame:CGRectMake(10,(30*i)+110,50,20)];    
    [btnphoto setTitle:@"Photo" forState:UIControlStateNormal];     
    [btnphoto setBackgroundColor:[UIColor redColor]]; 
    [btnphoto addTarget:self action:@selector(buttonPressPickColor:)
               forControlEvents:UIControlEventTouchUpInside];  
    btnphoto.tag=100 + i;
    [self.view addSubview:btnphoto];
}

-(IBAction)buttonPressPickColor:(UIButton*)sender
{   
    btnphoto.tag = sender.tag;
    NSLog(@"Btn photo Tag = %d",sender.tag);
    NEOColorPickerViewController *controller = [[NEOColorPickerViewController alloc] init];
    controller.delegate = self;
    controller.selectedColor = self.currentColor;
    controller.title = @"Color Picker";
    UINavigationController* navVC = [[UINavigationController alloc]initWithRootViewController:controller]; 
    [self presentViewController:navVC animated:YES completion:nil];
}

-(void)colorPickerViewController:(NEOColorPickerBaseViewController *)controller didSelectColor:(UIColor *)color 
{
    btnphoto.backgroundColor = color;  /// Important Line
    [controller dismissViewControllerAnimated:YES completion:nil];
}

1 个答案:

答案 0 :(得分:1)

最简单的方法是拥有一个实例变量/属性并将所选按钮的标记设置为它并使用该标记来获取正确的按钮实例...

例如:

在界面文件中:

@property (nonatomic, weak) int selectedTag;

以下是经过修改的代码,可以帮助您进一步

-(IBAction)buttonPressPickColor:(UIButton*)sender{   
_selectedTag = sender.tag;
NSLog(@"Btn photo Tag = %d",sender.tag);
NEOColorPickerViewController *controller = [[NEOColorPickerViewController alloc] init];
controller.delegate = self;
controller.selectedColor = self.currentColor;
controller.title = @"Color Picker";
UINavigationController* navVC = [[UINavigationController alloc]initWithRootViewController:controller]; 
[self presentViewController:navVC animated:YES completion:nil]; 
}
-(void)colorPickerViewController:(NEOColorPickerBaseViewController *)controller didSelectColor:(UIColor *)color {
UIButton *selectedButton = (UIbutton *)[self.view viewWithTag:_selectedTag];
selectedButton.backgroundColor = color;  /// Important Line
[controller dismissViewControllerAnimated:YES completion:nil]; }

希望这会有所帮助......