OGeek|极客世界-中国程序员成长平台

标题: UIButton点击的IOS回调 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 03:26
标题: UIButton点击的IOS回调

我有一个在我的应用程序的许多屏幕中使用的按钮。我想用自定义图像和按下按钮时的回调来实现一个自定义按钮。

我习惯了 java,但我不知道如何在 iOS 中解决这个问题。我已经阅读过关于 Category 和 Subclassing 的内容,但我仍然不确定。

有人有例子吗?或者什么是最好的解决方案?非常感谢任何帮助。

我做了什么(感谢@Aris):

.h 文件

#import <UIKit/UIKit.h>

@interface UIButton (MyUIButton)

+ (UIButton *)customButtonWithTargetid)target;

@end

.m 文件

#import "UIButton+MyUIButton.h"

@implementation UIButton (MyUIButton)

+ (UIButton *)customButtonWithTargetid)target{
    UIButton *button_ = [UIButton buttonWithType:UIButtonTypeSystem];
    [button_ setFrame:CGRectMake(0, 0, 120, 44)];
    [button_ setBackgroundImage:[UIImage imageNamed"button_image.png"] forState:UIControlStateNormal];

    [button_ addTarget:target
                actionselector(event_button_click
      forControlEvents:UIControlEventTouchUpInside];

    return button_;
}

@end

在我的 View Controller 中:

#import "UIButton+MyUIButton.h"

- (void)viewDidLoad {
    [super viewDidLoad];
UIButton *myButton = [UIButton customButtonWithTarget:self];
    [self.view addSubview:myButton];

}

-(void)event_button_click
{
    // code here
}

我收到此错误:'-[ViewController event_button_click:]: unrecognized selector sent to instance 0x78e5df10'



Best Answer-推荐答案


子类化 UIButton 是错误的方法。您需要添加一个类别工厂方法,该方法创建一个具有您需要的属性的按钮。 扩展 JNYJ 的答案:

+ (UIButton *)customButtonWithTargetid)target{
    UIButton *button_ = [UIButton buttonWithType:UIButtonTypeCustom];
    [button_ setFrame:CGRectMake(0, 0, 120, 44)];
    [button_ setBackgroundImage:[UIImage imageWithContentsOfFile"File path"] forState:UIControlStateNormal];

    [button_ addTarget:target 
                actionselector(event_button_click 
      forControlEvents:UIControlEventTouchUpInside];

    return button;
}

您应该将此方法放在可以使用 Xcode 创建的 UIButton 类别中,然后将文件导入到创建按钮所需的所有位置。 导入类别后,您可以像这样调用方法:

[UIButton customButtonWithTarget:target];

您必须确保 target 实现名为 event_button_click: 的方法。

在典型场景中,Button 的目标应该是负责 View 的 viewController。如果您希望 Button 在所有 ViewControllers 上执行相同的操作,那么 ViewControllers 应该是实现公共(public)操作的 ViewController 的子类。

实现此目的的另一种方法是将目标设置为您知道将在整个应用程序生命周期中存在的对象。候选人可以是 Application Delegate 或其他单例。

响应 OP 的编辑:

您收到此错误的错误是因为选择器末尾有“:”。 这意味着该方法应采用 1 个参数。 响应按钮点击的典型方法具有以下签名:

- (void)didTapButtonid)sender

其中 sender 是生成事件的对象,在我们的例子中是按钮。

所以在你的情况下:

-(void)event_button_clickid)sender
{
    UIButton * myButton = sender
    //custom code
}

关于UIButton点击的IOS回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26990358/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4