• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

UIButton点击的IOS回调

[复制链接]
菜鸟教程小白 发表于 2022-12-13 03:26:24 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

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

我习惯了 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap