swift交流群:342581988,欢迎增加。
刚刚写的小 demo。搞得还是不是太好。请大家拍砖!
能够直接复制执行
import UIKit class ViewController: UIViewController { var l : UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let labelRect = CGRectMake(140,75,50,50) var label = UILabel(frame : labelRect) label.backgroundColor = (UIColor.cyanColor()) self.view.addSubview(label) l = label var rect = CGRectMake(150,340,50,50) var upButton = UIButton(frame: rect) upButton.setTitle("up", forState: UIControlState.Normal) upButton.setTitleColor(UIColor.blueColor(),forState: UIControlState.Normal) upButton.tag = 1 upButton.setTitleColor(UIColor.blackColor(),forState: UIControlState.Highlighted) self.view.addSubview(upButton) upButton.addTarget(self,action:"moveClick:",forControlEvents:UIControlEvents.TouchUpInside); rect = CGRectMake(150,420,50,50) var downButton = UIButton(frame: rect) downButton.setTitle("down", forState: UIControlState.Normal) downButton.setTitleColor(UIColor.blueColor(),forState: UIControlState.Normal) downButton.tag = 2 downButton.setTitleColor(UIColor.blackColor(),forState: UIControlState.Highlighted) self.view.addSubview(downButton) downButton.addTarget(self,action:"moveClick:",forControlEvents:UIControlEvents.TouchUpInside) rect = CGRectMake(80,380,50,50) var leftButton = UIButton(frame: rect) leftButton.setTitle("left", forState: UIControlState.Normal) leftButton.setTitleColor(UIColor.blueColor(),forState: UIControlState.Normal) leftButton.tag = 3 leftButton.setTitleColor(UIColor.blackColor(),forState: UIControlState.Highlighted) self.view.addSubview(leftButton) leftButton.addTarget(self,action:"moveClick:",forControlEvents:UIControlEvents.TouchUpInside) rect = CGRectMake(220,380,50,50) var rigthButton = UIButton(frame: rect) rigthButton.setTitle("right", forState: UIControlState.Normal) rigthButton.setTitleColor(UIColor.blueColor(),forState: UIControlState.Normal) rigthButton.tag = 4 rigthButton.setTitleColor(UIColor.blackColor(),forState: UIControlState.Highlighted) self.view.addSubview(rigthButton) rigthButton.addTarget(self,action:"moveClick:",forControlEvents:UIControlEvents.TouchUpInside) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func moveClick(sender : UIButton!){ var centerPoint = l.center if sender.tag == 1{ var newPoint = CGPointMake(centerPoint.x, centerPoint.y-1) l.center = newPoint }else if sender.tag == 2{ var newPoint = CGPointMake(centerPoint.x, centerPoint.y+1) l.center = newPoint }else if sender.tag == 3{ var newPoint = CGPointMake(centerPoint.x-1, centerPoint.y) l.center = newPoint }else if sender.tag == 4{ var newPoint = CGPointMake(centerPoint.x+1, centerPoint.y) l.center = newPoint } } }
时间: 2024-11-04 06:10:01