草庐IT

ios - swift 的新手 : Why is the Timer not updating to the UILabel?

coder 2023-09-10 原文

我正在尝试使用 swift 制作自定义时钟。我最初是用 python 编写的,但认为这将是学习一门新语言的好机会,但我对它进行了粗略的尝试。我已经阅读了很多关于使用 Timer() 的很好的答案,但似乎没有任何效果;它会更新一次并保持静态。到目前为止,这是我的代码:

import UIKit
import Foundation


class ViewController: UIViewController {

@IBOutlet weak var timeLabel: UILabel!
let clock = MarsTime()
var timer: Timer?

override func viewDidLoad() {
    super.viewDidLoad()

    timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] timer in
        self?.updateTimeLabel()
            }



}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    updateTimeLabel()


}

@objc func updateTimeLabel() {

    let millis = clock.currentTimeMillis()
    let jdUT = clock.julianDateUT(millis: millis)
    let jdTT = clock.julianDateTT(julianDateUT: jdUT)
    let mct = clock.marsCoordinatedTime(julianDateTT: jdTT)
    var mctClockTime = clock.clockTime(mct: mct)
    let hour = mctClockTime[0]
    let min = mctClockTime[1]
    let sec = mctClockTime[2]
    timeLabel.text = "\(hour):\(min):\(sec)"
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

}

感谢您提供的任何帮助!

更新:我也包含了 MarsTime 代码

class MarsTime {

//---------------------------------\\
// Configure Earth Time Functions  \\
//---------------------------------\\

let date = Date().timeIntervalSince1970



func currentTimeMillis() -> (Int) {// Convert time to milliseconds
    let currentTimeMillis = Int(date * 1000)
    return (currentTimeMillis)
}

func julianDateUT(millis: Int) -> (Double) { // Convert julian date universial time
    let julianDateUT = 2440587.5 + (Double(millis) / (8.64 * pow(10, 7)))
    return (julianDateUT)
}

func julianDateTT(julianDateUT: Double) -> (Double) {// Convert to julian date Terrestrial time
    let julianDateTT = julianDateUT + ((32.184 + 37.0) / (86400.0))
    return (julianDateTT)
}

func deltatJ2000(julianDateTT: Double) -> (Double) {// Calculate time offset from J2000 Epoch
    let deltatJ2000 = julianDateTT - 2451545.0
    return (deltatJ2000)
}
//---------------------------------\\
//Configure Martian Time Fucntions \\
//----------------------------------\\

func marsMeanAnomaly(deltatJ2000: Double) -> (Double) { // Calculate the mean anomaly of the martian orbit
    let maUncorrected = 19.3871 + 0.52402073*(deltatJ2000)
    let n360s = Int( maUncorrected / 360.0) * 360
    let marsMeanAnomaly = maUncorrected - Double(n360s)
    return marsMeanAnomaly
}

func angleFictionMeanSun(deltatJ2000: Double) -> (Double) {  // Calulate angle of diction mean sun
    let afmsUncorrected = 270.3871 + 0.524038496*(deltatJ2000)
    let n360s = Int(afmsUncorrected / 360.0) * 360
    let angleFictionMeanSun = afmsUncorrected - Double(n360s)
    return (angleFictionMeanSun)
}

func perturbers(deltatJ2000: Double) -> (Double) { // Calculate perturbers
    let pbs = 0.0071 * cos(.pi / 180.0 * (((0.985626*deltatJ2000)/2.2353) + 49.409)) +
        0.0057 * cos(.pi / 180.0 * (((0.985626*deltatJ2000)/2.7543) + 168.173)) +
        0.0039 * cos(.pi / 180.0 * (((0.985626*deltatJ2000)/1.1177) + 191.837)) +
        0.0037 * cos(.pi / 180.0 * (((0.985626*deltatJ2000)/15.7866) + 21.736)) +
        0.0021 * cos(.pi / 180.0 * (((0.985626*deltatJ2000)/2.1354) + 15.704)) +
        0.0020 * cos(.pi / 180.0 * (((0.985626*deltatJ2000)/2.4694) + 95.528)) +
        0.0018 * cos(.pi / 180.0 * (((0.985626*deltatJ2000)/32.8493) + 49.095))
    return (pbs)
}

func v_M(deltatJ2000: Double, pbs: Double, marsMeanAnomaly: Double) -> (Double) { // Determine the equation of center
    let A = (10.691 + (3*pow(10, -7))*deltatJ2000)
    let B = Int((10.691 + (3*pow(10, -7))*deltatJ2000) / 360)*360
    let leadingConstant = A + Double(B)
    let v_M = (leadingConstant)*sin(.pi / 180.0 * (marsMeanAnomaly)) +
        0.623*sin(.pi / 180.0 * (2*marsMeanAnomaly)) + 0.050*sin(.pi / 180.0 * (3*marsMeanAnomaly)) +
        0.005*sin(.pi / 180.0 * (4*marsMeanAnomaly)) + 0.0005*sin(.pi / 180.0 * (5*marsMeanAnomaly)) +
    pbs
    return (v_M)
}

func aerocentSolarLong(angleFictionMeanSun: Double, v_M: Double) -> (Double) {
    let l_s = (angleFictionMeanSun + v_M) - Double(Int((angleFictionMeanSun + v_M) / 360)*360)
    return (l_s)
}

func martianEquationOfTime(l_s: Double, v_M: Double) -> (Double) {
    let eot = 2.861*sin(.pi / 180.0 * (2*l_s)) - 0.071*sin(.pi / 180.0 * (4*l_s)) +
        0.002*sin(.pi / 180.0 * (6*l_s)) - v_M
    return (eot)
}



func marsCoordinatedTime(julianDateTT: Double) -> (Double) {
    let mct = (24.0 * (((julianDateTT - 2451549.5) / 1.0274912517) + 44769.0 - 0.0009626))
    let mctFinal = mct.truncatingRemainder(dividingBy: 24.0)
    return (mctFinal)
}

func localMeanSolarTime(mct: Double, deg: Double) -> (Double)  { // Solar time for any longtitude west of the prime meridian
    let lmst = mct - deg*(1.0 / 15.0)
    return (lmst)
}


func marsDistance(ma: Double) -> (Double) {
    let helioDistance = 1.5236*(1.00436 - 0.09309*cos(.pi / 180.0 * (ma))
        - 0.00436*cos(.pi / 180.0 * (2*ma)) - 0.00031*cos(.pi / 180.0 * (3*ma)))
    return (helioDistance)
}

//-------------------------\\
// Configure Clock Display \\
//-------------------------\\
func clockTime(mct: Double) -> Array<String> {


    let mctStr = String(mct)
    var strHours = mctStr.components(separatedBy: ".")
    var mctHours  = strHours[0]
    var strMin = String(60 * Double("." + strHours[1])!).components(separatedBy: ".")
    var mctMin = strMin[0]
    var strSec = String(60 * Double("." + strMin[1])!).components(separatedBy: ".")
    var mctSec = strSec[0]
    let sec = mctSec.characters.count
    let min =  mctMin.characters.count
    let hour = mctHours.characters.count
    if 1 <= sec && sec < 2 {
        mctSec = "0" + mctSec
    } else if mctSec.characters.count < 1 {
        mctSec = "00"
    }
    if 1 <= min && min < 2 {
        mctMin = "0" + mctMin
    } else if mctMin.characters.count < 1 {
        mctMin = "00"
    }
    if 1 <= hour && hour < 2 {
        mctHours = "0" + mctHours
    } else if hour < 1 {
        mctHours = "00"
    }

    let mctClockTime = [mctHours , mctMin ,  mctSec]
    return (mctClockTime)
}
}

最佳答案

您的计时器工作正常。您的标签每秒都在更新,但它总是更新为相同的值。

问题是当您创建MarsTime 对象时,您只计算了一次date

解决这个问题的一种方法是使 date 成为一个计算属性,每次读取时总是返回当前时间:

var date: TimeInterval { return Date().timeIntervalSince1970 }

关于ios - swift 的新手 : Why is the Timer not updating to the UILabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44486553/

有关ios - swift 的新手 : Why is the Timer not updating to the UILabel?的更多相关文章

  1. ruby-on-rails - Rails 应用程序中的 Rails : How are you using application_controller. rb 是新手吗? - 2

    刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr

  2. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  3. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  4. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  5. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  6. ruby-on-rails - ruby 新手,有人可以帮我从控制台破译这个错误吗? - 2

    我真的只是不确定这意味着什么或我应该做什么才能让网页在我的本地主机上运行。现在它只是显示一个错误,上面写着“我们很抱歉,但出了点问题。”当我运行railsserver并在chrome中打开localhost:3000时。这是控制台输出:StartedGET"/users/sign_in"for127.0.0.1at2013-07-0512:07:07-0400ProcessingbyDevise::SessionsController#newasHTMLCompleted500InternalServerErrorin55msNoMethodError(undefinedmethod`

  7. ruby-on-rails - Rails 新手 : Recommendations for error handling in controller - 2

    抱歉,如果问题很明显,我才刚刚开始使用Rails。我现在在几个Controller方法中有以下代码:respond_todo|format|if@project.saveformat.html{redirect_to(edit_project_url(@project),:notice=>'#{user.name}addedto#{role}.')}format.jselseformat.html{render:action=>"edit"}format.js#...endend那么问题来了,对于所有方法中的错误,最好的方法是什么?是否建议我使用save!并在rescue_action

  8. ruby - 为 IO::popen 拯救 "command not found" - 2

    当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby​​1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#

  9. ruby - IO::EAGAINWaitReadable:资源暂时不可用 - 读取会阻塞 - 2

    当我尝试使用“套接字”库中的方法“read_nonblock”时出现以下错误IO::EAGAINWaitReadable:Resourcetemporarilyunavailable-readwouldblock但是当我通过终端上的IRB尝试时它工作正常如何让它读取缓冲区? 最佳答案 IgetthefollowingerrorwhenItrytousethemethod"read_nonblock"fromthe"socket"library当缓冲区中的数据未准备好时,这是预期的行为。由于异常IO::EAGAINWaitReadab

  10. ruby - 如何使用 ruby​​ fibers 避免阻塞 IO - 2

    我需要将目录中的一堆文件上传到S3。由于上传所需的90%以上的时间都花在了等待http请求完成上,所以我想以某种方式同时执行其中的几个。Fibers能帮我解决这个问题吗?它们被描述为解决此类问题的一种方法,但我想不出在http调用阻塞时我可以做任何工作的任何方法。有什么方法可以在没有线程的情况下解决这个问题? 最佳答案 我没有使用1.9中的纤程,但是1.8.6中的常规线程可以解决这个问题。尝试使用队列http://ruby-doc.org/stdlib/libdoc/thread/rdoc/classes/Queue.html查看文

随机推荐