Swift 3 - Label.Text 的 DateComponents 有时显示“...”

Swift 3 - DateComponents to Label.Text sometimes displays "..."

这让我发疯。

我正在尝试找出当前时间的两倍与最终将从服务器获取的设定时间之间的差异。

这是时间 getTimeDifference() 函数,目前它没有参数。

let formatter = DateFormatter()
let userCalender = Calendar.current;
let requestedComponent : Set<Calendar.Component> = [.month,.day,.hour,.minute,.second]


public func getTimeDifference() -> DateComponents
{
    formatter.dateFormat = "MM/dd/yyyy hh:mm:ss a"

    let _startTime = Date()
    let _endTime = formatter.date(from: "12/05/2016 14:01:00 a")


    let timeDifference = userCalender.dateComponents(requestedComponent, from: _startTime, to: _endTime!)
    return timeDifference
}

这就是我的 HomepageViewController

@IBOutlet weak var labelHours: UILabel!
@IBOutlet weak var labelMinutes: UILabel!
@IBOutlet weak var labelSeconds: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true).fire()
    // Do any additional setup after loading the view.
}

func updateCountdown() -> Void {

    let time = Countdown().getTimeDifference()

    labelHours.text = time.hour?.description
    labelMinutes.text = time.minute?.description
    labelSeconds.text = time.second?.description
}

每当我 运行 这段代码时,它可能会在几秒钟内完全正常工作,但是它会显示一些时间间隔 ...

问号 (?) 生成上面的图像并删除 (?) 将所有标签设置为 ...

labelHours.text = time.hour?.description
labelMinutes.text = time.minute?.description
labelSeconds.text = time.second?.description

labelHours.text = time.hour.description
labelMinutes.text = time.minute.description
labelSeconds.text = time.second.description

使框架适合文本的大小。您正在寻找的是:

questionsLabel.adjustsFontSizeToFitWidth = true

以上代码将更改字体大小以适应标签的宽度。并添加

questionsLabel.textAlignment = .center

它将在标签中正确呈现文本。