Wednesday, October 4, 2017

Swift đọc file txt

Hãy tạo một file txt có nội dung tùy ý, một bài thơ chẳng hạn, để Endcoding là UTF-8, kéo nó vào cây thư mục bên trái màn hình.

Ta sẽ đọc và set nó vào một textview.
Khai báo, định vị textView tên gi. Copy các dòng sau vào dưới dòng định vị textView
let path2 = NSBundle.mainBundle().pathForResource("t1", ofType: "txt")!
        var read : String = ""
      do {
        try read = NSString(contentsOfFile: path2, 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)")
        }
Nếu bạn để file txt trong một thư mục rồi mới kéo nó vào trong project, ví dụ thư mục tên raw thì hãy sửa chữ "t1" bên trong pathForResource thành "raw/t1",
Các dòng còn lại là ta đọc nó ra rồi set vào textView, để font nghiêng cỡ 17, đổ màu xanh và căn vào giữa.

Nếu ta muốn đọc file ra thành từng dòng và set mỗi dòng vào một phần từ mảng, ta làm như sau.
do {
            try read = NSString(contentsOfFile: path2, encoding: NSUTF8StringEncoding) as String
            var ar = read.componentsSeparatedByString("\n")
            let t=ar[1]
          
            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)")
        }
Ta đọc vào mảng ar và lấy ra dòng thứ hai, rồi set ra textView.

No comments:

Post a Comment