如何从UI按钮选择器调用方法?

时间:2013-07-16 20:14:57

标签: iphone ios objective-c methods

如何从我在下面的按钮选择器代码中调用此方法:

- (void)displayEditorForImage:(UIImage *)imageToEdit

{

    AFPhotoEditorController *editorController = [[AFPhotoEditorController alloc] initWithImage:imageToEdit];

    [editorController setDelegate:self];

    [self presentViewController:editorController animated:YES completion:nil];

}

这是UIButton我试图用以下方法调用该方法:

//edit button
UIButton *editButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[editButton addTarget:self
               action:@selector(editBtnTouch)
     forControlEvents:UIControlEventTouchDown];

[editButton setTitle:@"Effects" forState:UIControlStateNormal];


**// the following line shows the selector where I'm unsure how to call the method from the code above**
if ([[UIScreen mainScreen] respondsToSelector:@selector(displayEditorForImage:)] &&
        ([UIScreen mainScreen].scale == 2.0)) {
        // Retina display
        editButton.frame = CGRectMake(220.0, 320.0, 60.0, 40.0);


} else {
    editButton.frame = CGRectMake(220.0, 315.0, 60.0, 40.0);
}

[self.view addSubview:editButton];

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

当您调用添加到按钮的选择器时,如果选择器允许,则按钮本身将作为第一个参数传递。为了获得对图像的引用,您可能需要这样做(假设您想要的图像是按钮的背景图像):

- (void)displayEditorForImage:(UIButton*)sender {
    UIImage* imageToEdit = [sender backgroundImageForState:UIControlStateNormal];
    AFPhotoEditorController *editorController = [[AFPhotoEditorController alloc] initWithImage:imageToEdit];

    [editorController setDelegate:self];

    [self presentViewController:editorController animated:YES completion:nil];
}

或者你需要制作一个自定义的UIButton,它具有相关图像的额外属性,然后只需通过选择器中的按钮访问图像:

- (void)displayEditorForImage:(UIButton*)sender {
    if([sender isKindOfClass:[YourCustomButtonClass class]]) {
        UIImage* imageToEdit = ((YourCustomButtonClass*)sender).customImageProperty;

        AFPhotoEditorController *editorController = [[AFPhotoEditorController alloc] initWithImage:imageToEdit];

        [editorController setDelegate:self];

        [self presentViewController:editorController animated:YES completion:nil];
    }
}

编辑:

您似乎对如何在点击时UIButton调用方法感到困惑。您需要将定义方法的对象添加为按钮的目标(在本例中为self),将方法添加为选择器,并在点击按钮时调用方法使用UIControlEventTouchUpInside。所以你的代码是:

[editButton addTarget:self action:@selector(displayEditorForImage:) forControlEvents:UIControlEventTouchUpInside];