![](/img/trans.png)
[英]How to load txt file to UITextView with attributedString?
[英]How to save and load a .txt file with custom name?
我在应用程序中有一个弹出文本框警报,用户可以在其中输入字符来为.txt文件创建自定义名称,然后保存该文件。 该文件名存储在名为rideContent的全局变量中。 当我调用saveRide()函数时,充满字符串信息的文件存储在.txt中,并且应使用在文本框中创建的用户的文件名,但是存储在数组中的文件的名称为空。
我是在stopAction函数中无序地调用save函数还是太早了,这就是为什么数组为空的原因? 还是我以错误的方式调用了rideName = rideContent? 即rideName = rideContent [-1]?
我想要的是用户输入自定义名称,并将其用作保存和加载文件的标识符。 任何帮助将不胜感激!
在这里,我称一个名为rideContent的全局变量:
var rideContent = [String]()
我在这里调用保存功能:
@IBAction func stopAction(sender: UIButton) {
let alert = UIAlertController(title: "Ride Stopped", message: "Give a title to your ride", preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "Save", style: .Default,
handler: { (action:UIAlertAction) -> Void in
// Allow for text to be added and appended into the RideTableViewController
let textField = alert.textFields!.first
rideContent.append(textField!.text!)
// Update permanent storage after deleting a ride
NSUserDefaults.standardUserDefaults().setObject(rideContent, forKey: "rideContent")
// Segue to the Ride details page
self.performSegueWithIdentifier("ShowRideDetail", sender: nil)
})
let cancelAction = UIAlertAction(title: "Cancel",
style: .Default) { (action: UIAlertAction) -> Void in
}
alert.addTextFieldWithConfigurationHandler {
(textField: UITextField) -> Void in
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
//Show the alert
presentViewController(alert, animated: true, completion: nil)
// Stop the timer
timer.invalidate()
// Stop location updates
self.stopLocation()
// Save the ride
saveRide()
}
这是保存到文本文件的代码:
func saveRide() {
let rideName = rideContent
// Print Check
print("\(rideName) : the name of the saved ride")
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
let fileName = ("\(documentsDirectory)")+("\(rideName)")+(".txt")
print("\(fileName)This is firt check")
var content: String
// Adding elasped time information to the bicycle ride
// Content Order: Seconds, Minutes, Hours, Distance \n coordinates
content = ("\(seconds) Seconds, ")+("\(minutes) Minutes, ")+("\(hours) Hours, ") + ("\(self.distanceLabel.text!)") + "\n"
// Create a for loop to add each recorded coordinate value to the content list to later be added and displayed as a polyline
for coord in self.coords {
content = content + ("\(coord.latitude) " + "," + "\(coord.longitude) " + "\n")
}
do{
try content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding)
}catch _ {
}
}
这是用户可以在其中输入自定义名称的屏幕截图。 根据用户输入的乘车名称,是否在打印支票中将乘车名称称为“早晨乘车”?
这是在我的打印检查语句中打印到控制台的内容, []:已保存旅程的名称
您的“ saveRide()”函数将立即被调用。 将其放在块中,以便在saveAction上调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.