如何在Xcode中用Swift实现点击UIButton时向TextField插入当前时间?
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
dateFormatstring 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
相关产品推荐
相关产品推荐

