我的第一个Apple Watch小游戏——猜数字(Swift)

来源:互联网 发布:php站长工具源码 编辑:程序博客网 时间:2024/06/06 12:32

       这是一个在AppleWatch上实现的一个小型App,开发语言为Swift。是一个猜数字的游戏,屏幕上会出现不同数字的滚动,并能控制游戏的开始结束,让别人来猜数字。是不是很有意思。还可以多个人来玩这个游戏,比大家谁最后的数字大。 该应用我已经上传至 https://github.com/chenyufeng1991/GuessNumber   。

      由于该应用我主要是在Watch上实现的,所以在手机上不会有任何的效果,只会有一个白色的界面而已。实现步骤如下:

(1)新建一个iOS中的Apple Watch应用,如图:


(2)然后导入3张图片,分别标示1,2,3. 在Interface.storyboard中设计如下:


(3)在InterfaceController.swift中实现如下:

import WatchKitimport Foundationclass InterfaceController: WKInterfaceController {    @IBOutlet var image: WKInterfaceImage!  @IBOutlet var button: WKInterfaceButton!    //定时器;  var timer:NSTimer!    //判断是开始还是结束轮播;  var isStart:Bool = true    //图片下标;  var index:Int = 1      override func awakeWithContext(context: AnyObject?) {    super.awakeWithContext(context)        // Configure interface objects here.  }    override func willActivate() {    // This method is called when watch view controller is about to be visible to user    super.willActivate()  }    override func didDeactivate() {    // This method is called when watch view controller is no longer visible    super.didDeactivate()  }      @IBAction func buttonClicked() {        if(isStart){//开始滚动图片            addTimer()      button.setTitle("结束")          }else{//停止滚动图片      self.timer.invalidate()      self.timer = nil      button.setTitle("开始")          }        isStart = !isStart  }      func addTimer(){   //图片轮播的定时器;    self.timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "nextImage:", userInfo: nil, repeats: true)  }        func nextImage(sender:AnyObject!){        let str = "img" + String(index)        image.setImageNamed(str)        index++    if(index == 4){            index = 1    }      }          }

(4)实现效果如下:




github主页:https://github.com/chenyufeng1991  。欢迎大家访问!


4 0
原创粉丝点击