【问题标题】:Swift 3 - DateComponents to Label.Text sometimes displays "..."Swift 3 - 到 Label.Text 的 DateComponents 有时会显示“...”
【发布时间】:2017-04-18 19:30:02
【问题描述】:

这让我发疯了。

我试图找出当前时间的两倍和最终将从服务器获取的设定时间的差异。

这是时间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

【问题讨论】:

  • 每个 UILabel 是否有足够的宽度容纳两位数? (例如“24”需要比“11”更大的宽度。)

标签: ios swift xcode swift3 nsdatecomponents


【解决方案1】:

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

questionsLabel.adjustsFontSizeToFitWidth = true

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

questionsLabel.textAlignment = .center

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-29
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多