Drag a txt file in to project.
Declare a textView name gi. Copy in to
viewDidLoad.
let path = NSBundle.mainBundle().pathForResource("t1", ofType: "txt")!
var read : String = ""
do {
try read = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
gi.text = read
gi.font = UIFont.italicSystemFontOfSize(17)
gi.textColor = UIColor.blueColor()
gi.textAlignment = NSTextAlignment.Center
}
catch let error as NSError {
// print("ERROR :
reading from file \(fileName) : \(error.localizedDescription)")
}
If you put txt inside a folder, for example, raw folder, let change "t1" near pathForResource to "raw/t1"
If want to read file to lines and add to an array, use this
code.
do {
try read = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
var ar = read.componentsSeparatedByString("\n")
let t=ar[2]
gi.text = t
gi.font = UIFont.italicSystemFontOfSize(17)
gi.textColor = UIColor.blueColor()
gi.textAlignment = NSTextAlignment.Center
}
catch let error as NSError {
// print("ERROR :
reading from file \(fileName) : \(error.localizedDescription)")
}
We read to an array and set row 3 to textView.
No comments:
Post a Comment