How to set colour on a button from colour picker methods?

别说谁变了你拦得住时间么 提交于 2019-12-11 07:25:47

问题


I generate some buttons in a for loop, each with its own tag. Now I want to tap on a button and open a colour picker and set the colour of the button.

My problem is that when I open the colour picker and choose a color it gets set on a different button. I want to tap on a button and choose the colour for the tapped button only.

The code i am using is:

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:


Easiest thing would be to have a instance variable/property and set your selected button's tag to it and use that tag to get the correct instance of button...

For example:

In interface file:

@property (nonatomic, weak) int selectedTag;

Below is the modified code which gonna help you further

-(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]; }

Hope this helps...



来源:https://stackoverflow.com/questions/20163811/how-to-set-colour-on-a-button-from-colour-picker-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!