UI_Target-Action

本文介绍如何使用UIView自定义一个类似UIButton的控件,并通过添加目标和动作实现点击效果。文章详细展示了自定义按钮的创建过程及如何为按钮设置响应事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过UIView来模拟一个button的点击

#import <UIKit/UIKit.h>

@interface MyButton : UIView

// 通过MyButton实现button的点击效果
// 1.通过自定义的方法,把目标和动作传到类的内部
- (void)addNewTarget:(id)target Action:(SEL)action;
// target目标,button执行哪一个类的方法,对应的目标就是那个类的对象
// action动作,让button具体做什么事,执行的方法就是对应的动作

// 2.通过两条属性,把对应的目标和动作保存起来
@property(nonatomic, assign)id target;
@property(nonatomic, assign)SEL action;

@end
#import "MyButton.h"

@implementation MyButton

- (void)addNewTarget:(id)target Action:(SEL)action
{
// 3.实现对应的自定义方法,并且让两个属性来保存对应的目标和动作
    self.target = target;
    self.action = action;
}

// 4.给Button一个触发的条件, 重写触摸开始方法,只要一触碰视图,就调用touchesBegan方法,让button执行相应的点击方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 5.类把它的方法,交给MyButton来完成
    [self.target performSelector:self.action withObject:self];
}

@end
#import "MainViewController.h"
#import "MyButton.h"
#import "TestButton.h"
@interface MainViewController ()

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 通过UIView来模拟一个button的点击
    MyButton *mybutton = [[MyButton alloc] initWithFrame:CGRectMake(120, 100, 150, 40)];
    mybutton.backgroundColor = [UIColor magentaColor];
    [self.view addSubview:mybutton];
    [mybutton release];

    // 6.使用自定义的初始化方法
    [mybutton addNewTarget:self Action:@selector(click1:)];

    TestButton *testButton = [[TestButton alloc] initWithFrame:CGRectMake(120, 200, 150, 40)];
    testButton.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:testButton];
    [testButton release];

    [testButton addNewTarget:self Action:@selector(click2:)];
}

- (void)click1:(MyButton *)button
{
    NSLog(@"实现点击效果");
}

- (void)click2:(TestButton *)button
{
    NSLog(@"测试成功");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值