let btn1 = UIButton.buttonWithType(.System) as UIButton btn1.backgroundColor = UIColor.redColor() btn1.setTitle("Button1", forState: UIControlState.Normal) btn1.frame = CGRect(x: 10, y: 80, width: 300, height: 30) btn1.tag = 100 self.view.addSubview(btn1) let btn2 = UIButton.buttonWithType(.System) as UIButton btn2.backgroundColor = UIColor.blueColor() btn2.setTitle("Button2", forState: UIControlState.Normal) btn2.setTitleColor(UIColor.redColor(), forState: .Normal) // set round corner btn2.layer.cornerRadius = 10.0 btn2.frame = CGRect(x: 10, y: 120, width: 300, height: 30) btn2.tag = 101 self.view.addSubview(btn2) let btn3 = UIButton.buttonWithType(.System) as UIButton btn3.setTitle("Button3", forState: UIControlState.Normal) btn3.layer.cornerRadius = 10.0 // set border btn3.layer.borderWidth = 1 btn3.layer.borderColor = UIColor.blueColor().CGColor btn3.frame = CGRect(x: 10, y: 160, width: 300, height: 30) btn3.tag = 102 self.view.addSubview(btn3) // set listeners // Selector is a struct it convert a string to C pointer btn1.addTarget(self, action: Selector("onBtnClick:"), forControlEvents: UIControlEvents.TouchUpInside) btn2.addTarget(self, action: Selector("onBtnClick:"), forControlEvents: UIControlEvents.TouchUpInside) btn3.addTarget(self, action: Selector("onBtnClick:"), forControlEvents: UIControlEvents.TouchUpInside)
点击事件
func onBtnClick(btn:UIButton){ var msg = "" switch btn.tag{ case 100: msg = "you clicked button1" case 101: msg = "you clicked button2" case 102: msg = "you clicked button3" default: println("default") } // In IOS8 the UIAlertView is deprecated // now we use UIAlertController var alert = UIAlertController(title: "Alert", message: msg, preferredStyle: UIAlertControllerStyle.Alert) var ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{ (action) in println("you clicked ok") }) alert.addAction(ok) self.presentViewController(alert, animated: true) }
代码地址 https://github.com/lesliebeijing/IOSWithSwiftShowcase.git
(一)UI 篇之 Button
时间: 2024-11-01 19:37:35