Friday, February 22, 2019

Swift read poem app (2)

We want user can swipe to next poem in the list.
We will use GestureRecognizer to do.
Copy array poem name qua2 to reading class and declare 4 more arrays.
var qua2=["Bài một","Bài hai","Bài ba","Bài bốn","Bài năm","Bài sáu","Bài bảy","Bài tám"]
var ten2 = [String](count: 8, repeatedValue: " ")
var tacgia2 = [String](count: 8, repeatedValue: " ")
var ar2 = [String](count: 8, repeatedValue: " ")
var noidung = [String](count: 8, repeatedValue: " ")
Declare 2 variables.
var vi=0
var so2=0
Now we read all contents to array  noidung, one poem to one element.
Copy in to viewDidLoad
for i in0..<ar.count {
let path2 = NSBundle.mainBundle().pathForResource(ar[i], ofType: "txt")!
var rea2 : String = ""
var  t = ""
do {
try rea2 = NSString(contentsOfFile: path2, encoding: NSUTF8StringEncoding) asString
 t=rea2
noidung[i]=t
        }
catchlet error asNSError {
// print("ERROR : reading from file \(fileName) : \(error.localizedDescription)")
        }
        }
Now we need to convert array, choosen poem will move to top, others continue after.
Copy to above the line set text to textView.
for i in0..<tacgia.count {
so2=so+i
if(so2>7){
so2=so2-8
 }
ten2[i]=qua2[so2]
tacgia2[i]=tacgia[so2]
ar2[i]=noidung[so2]
 }
Change the line set text to textView like this.
gi.text = ar2[0]
Now create function to open next poem when user touch screen, copy to outside viewDidLoad.
func tap2 (g:UIGestureRecognizer) {
vi=vi+1
if(vi>7){
vi=vi-8
        }
gi.text = ar2[vi]
la.text = ten2[vi]
la2.text = tacgia2[vi]
 }
When user touch screen, we increase count variable 1 number and set text from next element in arrays.
Copy in to viewDidLoad.
let t3 = UITapGestureRecognizer(target:self, action:#selector(fo.tap2(_:)))
 t3.numberOfTapsRequired=2
view.addGestureRecognizer(t3)
If set numberOfTapsRequired=1 mean one touch, 2 mean double touch.
If you like user swipe to next poem, you must create a back button because in part 1 we swipe back to previous screen.
After that, change function in swipe command to tap2 like this.
let t2 = UIPanGestureRecognizer(target:self, action:#selector(fo.tap2(_:)))

view.addGestureRecognizer(t2)



No comments:

Post a Comment