【问题标题】:Using a nested function as the selector of an action - swift使用嵌套函数作为动作的选择器 - swift
【发布时间】:2018-01-28 14:20:06
【问题描述】:

这是我的代码:

func didSelectLabel() {

    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 30))

    label.center = viewForEdit.center
    label.textAlignment = .center
    label.isUserInteractionEnabled = true

    func userDragged(gesture: UIPanGestureRecognizer) {

        let loc = gesture.location(in: self.viewForEdit)
        label.center = loc

    }

    gesture = UIPanGestureRecognizer(target: self, action: userDragged(gesture:))
    label.addGestureRecognizer(gesture)

    let alert = UIAlertController(title: "Write your text", message: "", preferredStyle: .alert)
    let continueAction = UIAlertAction(title: "Continue", style: .default) { (UIAlertAction) in

        label.text = alert.textFields?[0].text

    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    alert.addTextField { (textField) in

        textField.placeholder = "Write here"

    }

    alert.addAction(continueAction)
    alert.addAction(cancelAction)

    present(alert, animated: true, completion: nil)

    self.viewForEdit.addSubview(label)

}

我想使用

func userDragged(手势: UIPanGestureRecognizer)

作为

的选择器

gesture = UIPanGestureRecognizer(target: self, action: userDragged(gesture:))

问题是如果我运行代码它会崩溃说

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[TestApp.ViewControllerEditor userDragged:]:无法识别的选择器发送到实例 0x7fc6b3c282b0”

P.S. 我不能将函数“userDragged(gesture:)”放在函数“didSelectLabel()”之外,因为如果这样做,“label.center = loc”会返回错误。这是因为在函数 'didSelectLabel()' 内部调用了 'label'

【问题讨论】:

    标签: swift function


    【解决方案1】:

    最简单的方法是将你的函数移到didSelectLabel之外,并将其更改为:

    func userDragged(gesture: UIPanGestureRecognizer) {
        let loc = gesture.location(in: self.viewForEdit)
        let label = gesture.view as? UILabel
        label?.center = loc
    
    }
    

    【讨论】:

    • 有效!!!太感谢了。这几天我一直在为此苦苦挣扎……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 2012-10-05
    相关资源
    最近更新 更多