调用返回字符串的函数时,在swift中获取错误

时间:2017-07-11 00:13:31

标签: swift

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var swipeLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        swipeLabel.text = "0"
        let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector (ViewController.swipeReceive(sender:)))

        let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swipeReceive(sender:)))

        leftSwipe.direction = .left
        rightSwipe.direction = .right

        view.addGestureRecognizer(leftSwipe)
        view.addGestureRecognizer(rightSwipe)

        let  disPlaynumon = swipeReceive(sender: UISwipeGestureRecognizer) // Error here
        swipeLabel.text = disPlaynumon
    }

    func swipeReceive(sender:UISwipeGestureRecognizer) -> String
    {
        if(sender.direction == .left)
        {
            var disPlaynum = 0
            disPlaynum = disPlaynum-1
            return String(disPlaynum)
        }

        if(sender.direction == .right)
        {
            var disPlaynum = 0
            disPlaynum = disPlaynum+1
            return String(disPlaynum)
        }
return String("not right or left swiped")
    }
}

错误在线:

let  disPlaynumon = swipeReceive(sender: UISwipeGestureRecognizer)

错误是:

  

无法将'UISwipeGestureRecognizer.Type'类型的值转换为预期参数类型'UISwipeGestureRecognizer'

这个程序应该让用户向右滑动,然后标签显示加一,当向左,显示为负1,但是当我调用函数swipeReceive尝试获取将要获得的字符串时,我收到错误显示在标签上。

1 个答案:

答案 0 :(得分:0)

是的,你不能这样做。您正在尝试使用UISwipeGestureRecognizer调用此方法?该方法期待对象,并且您正在传递该类。在视图中滑动时将自动调用该方法。所以你能做的是:

import UIKit

class ViewController:UIViewController {     @IBOutlet weak var swipeLabel:UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    swipeLabel.text = "0"
    let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector (ViewController.swipeReceive(sender:)))

    let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swipeReceive(sender:)))

    leftSwipe.direction = .left
    rightSwipe.direction = .right

    view.addGestureRecognizer(leftSwipe)
    view.addGestureRecognizer(rightSwipe)

    //REMOVE THESE TWO FROM HERE
   // let  disPlaynumon = swipeReceive(sender: UISwipeGestureRecognizer) // Error here
    //swipeLabel.text = disPlaynumon

}

func swipeReceive(sender:UISwipeGestureRecognizer){
    var displayNum = 0
    if(sender.direction == .left){
        displayNum = displayNum - 1
    }

    if(sender.direction == .right){
        displayNum = displayNum + 1
    }
    swipeLabel.text = "\(displayNum)"
}


}