我正在将旧的ViewController中的一些代码移植到WKInterfaceController,并且很难访问beatPatternsArray的count和index。现在我只想让自定义功能通过4个不同的心率进行索引,然后再显示不同的心脏图像。我到目前为止做得对吗?
import WatchKit
import Foundation
struct BeatPattern {
var heartImage = WKInterfaceImage()
var description = "Normal"
var bpm = 80
var duration: Double {
return 60.0 / Double(bpm)
}
}
let redHeartFast = WKInterfaceImage()
let yellowHeartElevated = WKInterfaceImage()
let greenHeartNormal = WKInterfaceImage()
let purpleHeartSlow = WKInterfaceImage()
let blueHeartSedated = WKInterfaceImage()
class InterfaceController: WKInterfaceController {
@IBOutlet weak var heartSymbol: WKInterfaceImage!
// @IBOutlet weak var bpmLabel: WKInterfaceLabel!
var currentBeatPattern = BeatPattern()
var currentBeatPatternIndex = 0
var beatPatternsArray = [
BeatPattern(heartImage: redHeartFast, description: "Fast", bpm: 180),
BeatPattern(heartImage: yellowHeartElevated, description: "Elevated", bpm: 140),
BeatPattern(heartImage: greenHeartNormal, description: "Normal", bpm: 80),
BeatPattern(heartImage: purpleHeartSlow, description: "Slow", bpm: 55),
BeatPattern(heartImage: blueHeartSedated, description: "Sedated", bpm: 30)]
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
self.view.insertSubview(heartSymbol, atIndex: 1) // Error
}
override func willActivate() {
super.willActivate()
// iconLabel.frame = self.view.bounds // fix this, frame math definitely wont work.
//iconLabel.f
//iconLabel.textAlignment = .Center
//iconLabel.font = UIFont.boldSystemFontOfSize(132)
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
newBeat()
NSTimer.scheduledTimerWithTimeInterval(8,
target: self,
selector: Selector("newBeat"),
userInfo: nil,
repeats: true)
//beat()
}
func newBeat() {
if ++currentBeatPatternIndex == beatPatternsArray.count {
currentBeatPatternIndex = 0
}
currentBeatPattern = beatPatternsArray[currentBeatPatternIndex]
//bpmLabel.setText("\(currentBeatPattern.bpm)")
heartSymbol = currentBeatPattern.heartImage
}
答案 0 :(得分:0)
您将beatPatternsArray
声明为WKInterfaceImage
,但它似乎是BeatPattern
的数组。
你可以将其声明为[BeatPattern]
而不是WKInterfaceImage
,但是从初始化开始,Swift可以推断出类型。所以只需使用:
var beatPatternsArray = [
BeatPattern(heartImage: yellowHeartFast, description: "Fast", bpm: 180),
BeatPattern(heartImage: redHeartNormal, description: "Normal", bpm: 80),
BeatPattern(heartImage: purpleHeartSlow, description: "Slow", bpm: 55),
BeatPattern(heartImage: blueHeartSedated, description: "Fast", bpm: 30)]
(没有: WKInterfaceImage
)。
然后你就可以使用数组方法了:
let beatCount = beatPatternsArray.count
let beatCountWithCountFunction = count(beatPatternsArray)
let secondElement = beatPatternsArray[1]