For comparison, I developed a quick example for Android and iOS. In both apps, we add a clock that refreshes.
First in swift for ios. We need to add a UILabel in the view and name it timeLabel and create two files:
// in ViewController.swift
import UIKit
class ViewController: UIViewController {
// preparing interval to update clock
var timer: NSTimer?
// link UILabel with controller
@IBOutlet weak var timeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// create interval and define callback
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.updateTimeLabel), userInfo: nil, repeats: true)
}
// on app exit clear interval
deinit {
timer?.invalidate()
}
// callback function
func updateTimeLabel() {
// create a date format
let formatter = NSDateFormatter()
formatter.timeStyle = .MediumStyle
// update label
timeLabel.text = "\(formatter.stringFromDate(NSDate()))"
}
}
In Android Studio it is a little bit easier. There is a TextClock object that we will add in the view. We link this element into our controller and update the date format.
// in MainActivity
package com.example.patrick.clock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextClock;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get TextClock
TextClock clock = (TextClock) findViewById(R.id.textClock);
// set format
clock.setFormat12Hour("hh:mm:ss");
}
}
back