---
title: "如何给组件UIButton添加事件并传递参数"
author: "BlueSkator"
date: "2015-05-12T10:53:39Z"
tags: ["Button", "iOS", "事件"]
categories: ["移动开发"]
slug: "uibutton"
draft: false
lastmod: "2015-05-12T10:53:39Z"
id: 2210426
url: "https://blueskator.iteye.com/blog/2210426"
---

```
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(buttonX, buttonY, width, height)];  
//给button添加点击事件，action参数中写入事件执行方法  
[button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];  
//在button的tag中添加你需要传递的参数，目前资料中只有这种方法  
//你可以传入任意类型的参数  
[button setTag:100];  
//下面是action方法  
-(void)action:(id)sender{  
//这个sender其实就是UIButton，因此通过sender.tag就可以拿到刚才的参数  
    int i = [sender tag];  
}  
```