0

I am having trouble detecting swipes.

I am trying to make it so that if a user swipes to the left, then my selectedSegmentIndex would be incremented:

segment.selectedSegmentIndex+1

If they were to swipe to the right, then it would be decremented:

segment.selectedSegmentIndex-1

That is, the user not only can click the segment to change pages but also can swipe left or right to change the "segment selectedSegmentIndex"

How could I achieve this?

Below is my code for this project:

class RecipesTableViewController: UITableViewController {
@IBOutlet var myTableView: UITableView!
@IBOutlet var menuButton:UIBarButtonItem!
@IBOutlet weak var segment: UISegmentedControl!


var recipes:[Recipe] = [
    Recipe(name: "巧克力手工餅乾", type: "甜點", material: "1.無鹽奶油  150g\n2.低筋麵粉  275g\n3.可可粉  25g\n4.蛋  1顆\n5.細砂糖  100g\n6.泡打粉(可省)  1/2小匙", image: "ChocolateCookie.jpg", isFavor: false, amount:"", userPhoto:"小璧.jpg", userName:"小璧" ),
    //Recipes(name: "巧克力手工餅乾", type: "餅乾", material: "1.無鹽奶油\n2.低筋麵粉\n3.可可粉\n4.蛋\n5.細砂糖\n6.泡打粉(可省)", image: "ChocolateCookie.jpg", isVisited: false, amount:"150g\n275g\n25g\n1顆\n100g\n1/2小匙"),
    Recipe(name: "辣味雞肉義大利麵", type: "麵食", material: "1.義大利麵\n2.雞胸肉\n3.洋蔥\n4.白酒\n5.蘆筍\n6.鴻喜菇\n7.玉米筍\n8.甜椒\n9.鮮奶油\n10.奶油\n11.蒜碎\n12.花椒油\n13.義大利香料", image: "pasta.jpg", isFavor: false, amount:"180g\n50g\n15g\n50g\n15g\n10g\n10g\n5g\n150g\n10g\n5g\n20g\n2g", userPhoto:"Adrian Hsiao.jpg", userName:"Adrian Hsiao" ),
    Recipe(name: "巧克力戚風蛋糕(6吋)", type: "甜點", material: "1.低筋麵粉\n2.無糖可可粉\n3.植物油\n4.牛奶\n5.蛋黃\n6.蛋白\n7.細砂糖\n8.蛋糕裝飾(奶油)", image: "chocolateCake.jpg", isFavor: false, amount:"45g\n15g\n30g\n60g\n3個\n3個\n45g\n適量", userPhoto:"維尼Winnie.jpg", userName:"維尼Winnie" ),
    Recipe(name: "蜂蜜法式吐司磚", type: "早餐", material: "1.吐司\n2.蛋\n3.牛奶\n4.蜂蜜\n5.糖粉", image: "toaste.jpg", isFavor: false, amount:"2片\n1顆\n20CC\n依喜好\n依喜好", userPhoto:"Nico Sun 老孫妮可.jpg", userName:"Nico Sun 老孫妮可" ),
    Recipe(name: "焗烤海鮮筆管麵", type: "麵食", material: "1.筆管麵\n 2.洋蔥\n3.蛤蜊\n4.透抽\n5.鮮蝦\n6.蒜頭\n7.水\n8.康寶濃湯粉\n9.鹽\n10.起司絲\n11.煮熟綠花椰菜", image: "pasta2.jpg", isFavor: false, amount:"1/3包\n1顆\n適量\n適量\n適量\n三小瓣\n1杯半\n半包\n少許\n適量\n適量", userPhoto:"阿渝師~美味廚房.jpg", userName:"阿渝師~美味廚房" ),
    Recipe(name: "秀珍菇麻油雞", type: "冬令進補", material: "1.秀珍菇\n2.帶骨雞腿\n3.米酒\n4.麻油\n5.薑", image: "large_3649cc5a24aef9ec.jpg", isFavor: false, amount:"450g\n2隻\n600c.c\n6大匙\n1大塊", userPhoto:"小舖の廚房.jpg", userName:"小舖の廚房" ),
    Recipe(name: "清熱除痘湯", type: "夏日清爽", material: "1.花旗參\n2.蒟蒻\n3.豬肉\n4.紅棗\n5.薑\n6.鹽\n7.水", image: "soap.jpg", isFavor: false, amount:"23克\n38克\n150克\n4粒\n1片\n1茶匙\n10杯", userPhoto:"唐安麒超猛瘦身食譜.jpg", userName:"唐安麒超猛瘦身食譜" ),
    Recipe(name: "蜂蜜法式吐司磚", type: "早餐", material: "1.吐司\n2.蛋\n3.牛奶\n4.蜂蜜\n5.糖粉", image: "toaste.jpg", isFavor: false, amount:"2片\n1顆\n20CC\n依喜好\n依喜好", userPhoto:"Nico Sun 老孫妮可.jpg", userName:"Nico Sun 老孫妮可" ),
    Recipe(name: "蜂蜜法式吐司磚", type: "早餐", material: "1.吐司\n2.蛋\n3.牛奶\n4.蜂蜜\n5.糖粉", image: "toaste.jpg", isFavor: false, amount:"2片\n1顆\n20CC\n依喜好\n依喜好", userPhoto:"Nico Sun 老孫妮可.jpg", userName:"Nico Sun 老孫妮可" ),
   Recipe(name: "蜂蜜法式吐司磚", type: "早餐", material: "1.吐司\n2.蛋\n3.牛奶\n4.蜂蜜\n5.糖粉", image: "toaste.jpg", isFavor: false, amount:"2片\n1顆\n20CC\n依喜好\n依喜好", userPhoto:"Nico Sun 老孫妮可.jpg", userName:"Nico Sun 老孫妮可" )

    ]

var noodles:[Recipe] = [
    Recipe(name: "辣味雞肉義大利麵", type: "麵食", material: "1.義大利麵\n2.雞胸肉\n3.洋蔥\n4.白酒\n5.蘆筍\n6.鴻喜菇\n7.玉米筍\n8.甜椒\n9.鮮奶油\n10.奶油\n11.蒜碎\n12.花椒油\n13.義大利香料", image: "pasta.jpg", isFavor: false, amount:"180g\n50g\n15g\n50g\n15g\n10g\n10g\n5g\n150g\n10g\n5g\n20g\n2g", userPhoto:"Adrian Hsiao.jpg", userName:"Adrian Hsiao" ),
    Recipe(name: "焗烤海鮮筆管麵", type: "麵食", material: "1.筆管麵\n 2.洋蔥\n3.蛤蜊\n4.透抽\n5.鮮蝦\n6.蒜頭\n7.水\n8.康寶濃湯粉\n9.鹽\n10.起司絲\n11.煮熟綠花椰菜", image: "pasta2.jpg", isFavor: false, amount:"1/3包\n1顆\n適量\n適量\n適量\n三小瓣\n1杯半\n半包\n少許\n適量\n適量", userPhoto:"阿渝師~美味廚房.jpg", userName:"阿渝師~美味廚房" )
]

var snacks:[Recipe] = [
    Recipe(name: "巧克力手工餅乾", type: "甜點", material: "1.無鹽奶油  150g\n2.低筋麵粉  275g\n3.可可粉  25g\n4.蛋  1顆\n5.細砂糖  100g\n6.泡打粉(可省)  1/2小匙", image: "ChocolateCookie.jpg", isFavor: false, amount:"", userPhoto:"小璧.jpg", userName:"小璧" ),
    Recipe(name: "巧克力戚風蛋糕(6吋)", type: "甜點", material: "1.低筋麵粉\n2.無糖可可粉\n3.植物油\n4.牛奶\n5.蛋黃\n6.蛋白\n7.細砂糖\n8.蛋糕裝飾(奶油)", image: "chocolateCake.jpg", isFavor: false, amount:"45g\n15g\n30g\n60g\n3個\n3個\n45g\n適量", userPhoto:"維尼Winnie.jpg", userName:"維尼Winnie" )
]
//var recipesIsDone = [Bool](count: 21, repeatedValue: false)

@IBAction func changePage(sender: AnyObject) {
    if segment.selectedSegmentIndex == 0 {
        self.myTableView.reloadData()
        self.category = 0
        print(category)
        //self.performSegueWithIdentifier("showRecipesDetail", sender: self)
    }
    if segment.selectedSegmentIndex == 1 {
        self.myTableView.reloadData()
        self.category = 1
         print(category)
        //self.performSegueWithIdentifier("showRecipesDetail", sender: self)
    }
    if segment.selectedSegmentIndex == 2 {
        self.myTableView.reloadData()
        self.category = 2
        //self.performSegueWithIdentifier("showRecipesDetail", sender: self)
    }
    if segment.selectedSegmentIndex == 3 {
        self.myTableView.reloadData()
        self.category = 3
        //self.performSegueWithIdentifier("showRecipesDetail", sender: self)
    }
    if segment.selectedSegmentIndex == 4 {
        self.myTableView.reloadData()
        self.category = 4
       // self.performSegueWithIdentifier("showRecipesDetail", sender: self)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    //移除返回按鈕的標題
    self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: nil, action: nil)

    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())

    if revealViewController() != nil {
        //            revealViewController().rearViewRevealWidth = 62
        menuButton.target = revealViewController()
        menuButton.action = "revealToggle:"

        revealViewController().rightViewRevealWidth = 150

        view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

//下兩個為建立tableView cell時必須建立的兩個function
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section
   // if segment.selectedSegmentIndex == 1 {
    //}
    if segment.selectedSegmentIndex == 0 {
        return self.recipes.count
    }
    if segment.selectedSegmentIndex == 1 {
        return self.noodles.count
    }
    if segment.selectedSegmentIndex == 2 {
        return self.snacks.count
    }
    if segment.selectedSegmentIndex == 3 {
        return self.noodles.count
    }
    if segment.selectedSegmentIndex == 4 {
        return self.noodles.count
    }
    return self.recipes.count

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cellIdentifier = "Cell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CustomTableViewCell

    if segment.selectedSegmentIndex == 0 {
        let recipe = recipes[indexPath.row]
        cell.favorIconImageView.hidden = !recipe.isFavor
        cell.nameLabel.text = recipe.name
        cell.thumbnailImageView.image = UIImage(named: recipe.image)
        // cell.locationLabel.text = recipe.material
        cell.typeLabel.text = recipe.type
        cell.userPhoto.image = UIImage(named: recipe.userPhoto)
        cell.userName.text = recipe.userName
    }


    if segment.selectedSegmentIndex == 1 {
        let noodle = noodles[indexPath.row]
        cell.favorIconImageView.hidden = !noodle.isFavor
        cell.nameLabel.text = noodle.name
        cell.thumbnailImageView.image = UIImage(named: noodle.image)
        // cell.locationLabel.text = recipe.material
        cell.typeLabel.text = noodle.type
        cell.userPhoto.image = UIImage(named: noodle.userPhoto)
        cell.userName.text = noodle.userName
    }

    if segment.selectedSegmentIndex == 2 {
        let snack = snacks[indexPath.row]
        cell.nameLabel.text = snack.name
        cell.thumbnailImageView.image = UIImage(named: snack.image)
        // cell.locationLabel.text = recipe.material
        cell.typeLabel.text = snack.type
        cell.userPhoto.image = UIImage(named: snack.userPhoto)
        cell.userName.text = snack.userName
    }

    if segment.selectedSegmentIndex == 3 {
        let noodle = noodles[indexPath.row]
        cell.nameLabel.text = noodle.name
        cell.thumbnailImageView.image = UIImage(named: noodle.image)
        // cell.locationLabel.text = recipe.material
        cell.typeLabel.text = noodle.type
        cell.userPhoto.image = UIImage(named: noodle.userPhoto)
        cell.userName.text = noodle.userName
    }

    if segment.selectedSegmentIndex == 4 {
        let noodle = noodles[indexPath.row]
        cell.nameLabel.text = noodle.name
        cell.thumbnailImageView.image = UIImage(named: noodle.image)
        // cell.locationLabel.text = recipe.material
        cell.typeLabel.text = noodle.type
        cell.userPhoto.image = UIImage(named: noodle.userPhoto)
        cell.userName.text = noodle.userName
    }
    //I've been here
    //cell.accessoryType = recipesIsDone[indexPath.row] ? .Checkmark : .None
    //也可寫成
    /*
     if restaurantIsVisited[indexPath.rwo] {
     cell?.accessoryType = .Checkmark
     } else {
     cell?.accessoryType = .None
     }
     */


    //隱藏愛心圖片
    //cell.favorIconImageView.hidden = !recipe.isFavor


    /*
    //Circular image
    //cell.thumbnailImageView.layer.cornerRadius = 10.0
    cell.thumbnailImageView.layer.cornerRadius = cell.thumbnailImageView.frame.size.width / 2
    cell.thumbnailImageView.clipsToBounds = true
    */


    return cell
}


//滑動刪除
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    if editingStyle == .Delete {

        if segment.selectedSegmentIndex == 0{
            self.recipes.removeAtIndex(indexPath.row)
            //self.tableView.reloadData()
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        }
        if segment.selectedSegmentIndex == 1{
            self.noodles.removeAtIndex(indexPath.row)
            //self.tableView.reloadData()
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        }
        if segment.selectedSegmentIndex == 2{
            self.snacks.removeAtIndex(indexPath.row)
            //self.tableView.reloadData()
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        }
        if segment.selectedSegmentIndex == 3{
            self.noodles.removeAtIndex(indexPath.row)
            //self.tableView.reloadData()
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        }
        if segment.selectedSegmentIndex == 4{
            self.noodles.removeAtIndex(indexPath.row)
            //self.tableView.reloadData()
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        }



    }
}

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
    let doneAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "收藏", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in

        let cell = tableView.cellForRowAtIndexPath(indexPath) as! CustomTableViewCell

        switch self.segment.selectedSegmentIndex {
            case 0:
                let recipe = self.recipes[indexPath.row]
                recipe.isFavor = recipe.isFavor ? false : true
                cell.favorIconImageView.hidden = !recipe.isFavor
                print(recipe.isFavor)
            case 1:
                let noodle = self.noodles[indexPath.row]
                noodle.isFavor = noodle.isFavor ? false : true
                cell.favorIconImageView.hidden = !noodle.isFavor
                print(noodle.isFavor)
            case 2:
                let snack = self.snacks[indexPath.row]
                snack.isFavor = snack.isFavor ? false : true
                cell.favorIconImageView.hidden = !snack.isFavor
                print(snack.isFavor)

            default:
                /*let recipe = self.recipes[indexPath.row]
                recipe.isFavor = recipe.isFavor ? false : true
                cell.favorIconImageView.hidden = !recipe.isFavor
                print(recipe.isFavor)*/
                let noodle = self.noodles[indexPath.row]
                noodle.isFavor = noodle.isFavor ? false : true
                cell.favorIconImageView.hidden = !noodle.isFavor
                print(noodle.isFavor)
        }
        /*let recipe = self.recipes[indexPath.row]
        recipe.isFavor = recipe.isFavor ? false : true

        print(recipe.isFavor)*/

        //cell.accessoryType = self.recipesIsDone[indexPath.row] ? .Checkmark : .None


       }
    )

    var deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete",handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in

        //刪除列的資料
        switch self.segment.selectedSegmentIndex {
        case 0:
            self.recipes.removeAtIndex(indexPath.row)
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

        case 1:
            self.noodles.removeAtIndex(indexPath.row)
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        case 2:
            self.snacks.removeAtIndex(indexPath.row)
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

        default:
            self.noodles.removeAtIndex(indexPath.row)
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        }



    })

    //改變滑動按鈕的背景顏色
    doneAction.backgroundColor = UIColor(red: 255.0/255.0, green: 166.0/255.0, blue: 51.0/255.0, alpha: 1.0)
    //deleteAction.backgroundColor = UIColor(red: 51.0/255.0, green: 51.0/255.0, blue: 51.0/255.0, alpha: 1.0)

    //告訴表格滑動時要產生share跟delete的按鈕
    return [deleteAction, doneAction]
}

var category: Int = Int()
 //var : Int = Int()
//segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "showRecipesDetail" {
       // var obj = segue.destinationViewController as! DetailTableViewCell
        if let indexPath = self.tableView.indexPathForSelectedRow {
            let destinationController = segue.destinationViewController as! DetailViewController

            if segment.selectedSegmentIndex == 0 {
                destinationController.recipes = recipes[indexPath.row]
                destinationController.category = self.category
                print(category)
            }
            if segment.selectedSegmentIndex == 1 {
                destinationController.noodles = noodles[indexPath.row]
                destinationController.category = self.category
                 print(category)
            }
            if segment.selectedSegmentIndex == 2 {
                destinationController.snacks = snacks[indexPath.row]
                destinationController.category = self.category
                print(category)
            }
            if segment.selectedSegmentIndex == 3 {
                destinationController.noodles = noodles[indexPath.row]
                destinationController.category = self.category
            }
            if segment.selectedSegmentIndex == 4 {
                destinationController.noodles = noodles[indexPath.row]
                destinationController.category = self.category
            }
        }
    }

}




/*
//滑動隱藏導覽列
override func viewWillAppear(animated: Bool) {

    super.viewWillAppear(animated)
    self.navigationController?.hidesBarsOnSwipe = true

}
*/



}
Benjamin Lowry
  • 3,730
  • 1
  • 23
  • 27
HarryHuang
  • 77
  • 9
  • Have a look at this question and its answer: http://stackoverflow.com/questions/24215117/how-to-recognize-swipe-in-all-4-directions/24215844#24215844 It's possibly a duplicate – xpereta Oct 11 '16 at 14:58

1 Answers1

3

You might have to adapt the following answer a bit to your project since I am still not totally sure what you are trying to do, but this should be the general idea you are looking for:

in viewDidLoad:

 var swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.swipedRight))
swipeRight.direction = UISwipeGestureRecognizerDirection.Right

var swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.swipedLeft))
swipeLeft.direction = UISwipeGestureRecognizerDirection.Left

In your view controller:

func swipedRight(){
    segment.selectedSegmentIndex -= 1
}

func swipedLeft(){
    segment.selectedSegmentIndex += 1
}

Once you add swipe gesture recognizers, they will fire the action when the user swipes, calling the above functions, which will increment or decrement your variable.

NOTE:

Also, this doesn't relate to your question, but I noticed you have a lot of redundancy in your code. You should really think about trying to execute some of your tasks more efficiently. There are times in your code where you have extensive if statements that have identical code inside each bracket, which makes no sense.

For example, this segment of code:

if segment.selectedSegmentIndex == 0{
        self.recipes.removeAtIndex(indexPath.row)
        //self.tableView.reloadData()
        self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    }
    if segment.selectedSegmentIndex == 1{
        self.noodles.removeAtIndex(indexPath.row)
        //self.tableView.reloadData()
        self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    }
    if segment.selectedSegmentIndex == 2{
        self.snacks.removeAtIndex(indexPath.row)
        //self.tableView.reloadData()
        self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    }
    if segment.selectedSegmentIndex == 3{
        self.noodles.removeAtIndex(indexPath.row)
        //self.tableView.reloadData()
        self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    }
    if segment.selectedSegmentIndex == 4{
        self.noodles.removeAtIndex(indexPath.row)
        //self.tableView.reloadData()
        self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    }

Should just be able to be expressed like this inside that function with the same results:

self.noodles.removeAtIndex(indexPath.row)
        //self.tableView.reloadData()
        self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

You can also try setting values to variables e.g.

self.category = segment.selectedSegmentIndex 

So that you don't have to evaluate each value. Just a thought, but I think it would really help the readability of your code.

Benjamin Lowry
  • 3,730
  • 1
  • 23
  • 27
  • let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.swipedRight)) swipeRight.direction = UISwipeGestureRecognizerDirection.Right let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.swipedLeft)) swipeLeft.direction = UISwipeGestureRecognizerDirection.Left view.addGestureRecognizer(swipeRight) view.addGestureRecognizer(swipeLeft) – HarryHuang Oct 12 '16 at 04:55
  • 1
    func swipedRight(){ segment.selectedSegmentIndex -= 1 self.myTableView.reloadData() self.category = segment.selectedSegmentIndex print("Right") } func swipedLeft(){ segment.selectedSegmentIndex += 1 self.myTableView.reloadData() self.category = segment.selectedSegmentIndex print("Left") } – HarryHuang Oct 12 '16 at 04:55
  • @HarryHuang Great! Don't forget to mark your accepted answer so that future users can find the best answer quickly. Thanks :) – Benjamin Lowry Oct 12 '16 at 07:48