请教swift中,多按钮响应事件中,sefl传参的问题
答案:1 悬赏:70
解决时间 2021-02-20 08:55
- 提问者网友:骑士
- 2021-02-19 16:14
请教swift中,多按钮响应事件中,sefl传参的问题
最佳答案
- 二级知识专家网友:傲气稳了全场
- 2021-02-19 17:52
写了一个三按钮共用一个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)
}
}
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)
}
}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯
• 手机登qq时,显示手机磁盘不足,清理后重新登 |
• 刺客的套装怎么选啊? |