You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xcode中用Swift实现点击UIButton时向TextField插入当前时间?

Insert Current Time into UITextField When Tapping UIButton

Here's how you can modify your code to display the current time in your text field when the button is tapped:

Step 1: Fix the Outlet Reference

First, you had a small typo in your code—your text field outlet is named f1TextField, but you were referencing timeatf1TextField. Let's correct that and add the time formatting logic.

Step 2: Add Time Formatting Code

Update your markf1 IBAction with this code:

@IBOutlet weak var f1TextField: UITextField! 

@IBAction func markf1(_ sender: UIButton) {
    // Create a DateFormatter to format the time into a readable string
    let timeFormatter = DateFormatter()
    
    // Set your preferred time format (pick one or customize!)
    timeFormatter.dateFormat = "HH:mm:ss" // 24-hour format (e.g., 14:30:45)
    // OR use this for 12-hour with AM/PM: timeFormatter.dateFormat = "h:mm a" (e.g., 2:30 PM)
    
    // Get the current date/time and convert it to a formatted string
    let currentTimeString = timeFormatter.string(from: Date())
    
    // Assign the formatted time to your text field
    f1TextField.text = currentTimeString
    
    // Optional: Remove this line if you don't want the keyboard to pop up after setting the time
    // f1TextField.becomeFirstResponder()
}

Quick Tips:

  • Customize the Format: You can adjust the dateFormat string to match your needs. Some common options include:
    • "HH:mm": 24-hour time without seconds (e.g., 14:30)
    • "h:mm:ss a": 12-hour time with seconds and AM/PM (e.g., 2:30:45 PM)
  • Keyboard Behavior: If you only want to display the time (not let the user edit it right away), remove the becomeFirstResponder() line—it’s not necessary for just setting the text.

内容的提问来源于stack exchange,提问作者B. Deaton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:37:03