iphone - 如何从 UIbutton 选择器调用方法?

标签 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];

感谢帮助

最佳答案

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

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

关于iphone - 如何从 UIbutton 选择器调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17686122/

相关文章:

ios - 如何以编程方式获取 iPhone 的 IMEI 号码?

ios - subview 的 CGRectIntersectsRect

ios - 将NSString转换为NSDate并返回不同的格式NSString

objective-c - Objective C 中的内存管理问题

iphone - GDB:将 EXC_BAD_ACCESS 信号传递给程序

iphone - 应用程序在 [[NSBundle mainBundle] pathForResource 处崩溃

iphone - 如何让我的段 UISegmentedControl 响应?

ios - UIStatusBar 风格与 UINavigationBar 一致

ios - 使用未解析的标识符 FBSession

iphone - 以编程方式枚举 UIViewController 的传出 Segue