Я использую Xcode Version 11.0 (11A420a) и Swift для создания приложения для iPhone и Apple Watch. У меня есть код, который сделал простую метку таймера, кнопки запуска и остановки, и я хотел бы, чтобы он также был на Apple Watch.
В файле Xcode viewcontroller.swift у меня есть этот код, и он отлично работает.
var startTime = TimeInterval()
var startofTime = Date()
var timer:Timer = Timer()
var endTime: Date!
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var Start: UIButton!
@IBOutlet weak var Stop: UIButton!
@IBAction func startAct(_ sender: Any) {
alarmTime = Date()
startofTime = Date()
Start.isHidden = true
Stop.isHidden = false
if (!timer.isValid) {
let aSelector : Selector = #selector(ViewController.updateTime)
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = Date.timeIntervalSinceReferenceDate
}
}
@IBAction func stopAction(_ sender: Any) {
progressView.progress = 0.0
progress.completedUnitCount = 1024
Start.isHidden = false
Stop.isHidden = true
endTime = Date()
timer.invalidate()
}
@objc func updateTime() {
let currentTime = Date.timeIntervalSinceReferenceDate
//Find the difference between current time and start time.
var elapsedTime: TimeInterval = currentTime - startTime
// print(elapsedTime)
// print(Int(elapsedTime))
//calculate the hours in elapsed time.
let hours = UInt8(elapsedTime / 3600.0)
elapsedTime -= (TimeInterval(hours) * 3600)
//calculate the minutes in elapsed time.
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (TimeInterval(minutes) * 60)
//calculate the seconds in elapsed time.
let seconds = UInt8(elapsedTime)
elapsedTime -= TimeInterval(seconds)
//find out the fraction of milliseconds to be displayed.
let fraction = UInt8(elapsedTime * 100)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)
//concatenate minuets, seconds and milliseconds as assign it to the UILabel
timerLabel.text = "\(hours):\(strMinutes):\(strSeconds).\(strFraction)"
}
Когда я попытался скопировать его в часы InterfaceController.swift, я сделал большую часть этого,просто копирую и вставляю, но я получаю сообщение об ошибке с меткой.
! Невозможно присвоить значение: метод setText - это
Может кто-нибудь помочь мне с меткой для часов. Примерно так -
timerLabel.setText = "\(hours):\(strMinutes):\(strSeconds).\(strFraction)"
, если я просто поставлю
timerLabel.setText((strFraction))
Он работает для отображения миллисекунд, но id хотел бы объединить их все, пожалуйста.
Если я это сделаюthis
timerLabel.setText((strSeconds)(strFraction))
Я получаю эту ошибку
! Невозможно вызвать значение нефункционального типа 'String'
Это полный код отслеживания на данный момент, просто нужнопоследняя строка
//
// InterfaceController.swift
// WatchKit Extension
//
// Created by Kurt on 3/10/19.
// Copyright © 2019 Kurt. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
override func awake(withContext context: Any?) {
super.awake(withContext: 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()
}
var startTime = TimeInterval()
var startofTime = Date()
var timer:Timer = Timer()
var endTime: Date!
@IBOutlet weak var timerLabel: WKInterfaceLabel!
@IBAction func Start() {
startofTime = Date()
if (!timer.isValid) {
let aSelector : Selector = #selector(InterfaceController.updateTime)
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = Date.timeIntervalSinceReferenceDate
}
}
@objc func updateTime() {
let currentTime = Date.timeIntervalSinceReferenceDate
//Find the difference between current time and start time.
var elapsedTime: TimeInterval = currentTime - startTime
// print(elapsedTime)
// print(Int(elapsedTime))
//calculate the hours in elapsed time.
let hours = UInt8(elapsedTime / 3600.0)
elapsedTime -= (TimeInterval(hours) * 3600)
//calculate the minutes in elapsed time.
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (TimeInterval(minutes) * 60)
//calculate the seconds in elapsed time.
let seconds = UInt8(elapsedTime)
elapsedTime -= TimeInterval(seconds)
//find out the fraction of milliseconds to be displayed.
let fraction = UInt8(elapsedTime * 100)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)
//concatenate minuets, seconds and milliseconds as assign it to the UILabel
timerLabel.setText(\(hours):\(strMinutes):\(strSeconds).\(strFraction)) !error
}
}