请教swift中,多按钮响应事件中,sefl传参的问题
1个回答
展开全部
写了一个三按钮共用一个click函数的方式,click函数会捕捉到上面三个按钮的UIButton 对象,并访问其中的.tag属性,代码如下:
class ActionViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//红按钮
let redButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
redButton.frame = CGRectMake(0, 20, 100, 30)
redButton.setTitle("点我变红", forState: UIControlState.Normal)
redButton.backgroundColor = UIColor.redColor()
redButton.tag = 100
self.view.addSubview(redButton)
//蓝色按钮
let blueButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
blueButton.frame = CGRectMake(0, 60, 100, 30)
blueButton.setTitle("点我变蓝", forState: UIControlState.Normal)
blueButton.backgroundColor = UIColor.blueColor()
blueButton.tag = 101
self.view.addSubview(blueButton)
//绿色
let greenButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
greenButton.frame = CGRectMake(0, 100, 100, 30)
greenButton.setTitle("点我变绿", forState: UIControlState.Normal)
greenButton.backgroundColor = UIColor.greenColor()
greenButton.tag = 102
self.view.addSubview(greenButton)
redButton.addTarget(self, action: "click:", forControlEvents: UIControlEvents.TouchUpInside)
blueButton.addTarget(self, action: "click:", forControlEvents: UIControlEvents.TouchUpInside)
greenButton.addTarget(self, action: "click:", forControlEvents: UIControlEvents.TouchUpInside)
}
func click(btn:UIButton){
print(btn.tag)
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询