2017-08-20 7 views
0

は、これは私のコードです:アクションのセレクタとしてネストされた関数を使用して - SWIFT

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)を使用したいと思います

のセレクタを

ジェスチャー= UIPanGestureRecognizer(ターゲット:自己、アクション:userDragged(ジェスチャー:))

は、問題は、私は、コードを実行した場合、それがキャッチされない例外が原因アプリ 'NSInvalidArgumentException' を終了

を言ってクラッシュするということです理由: -

PS '[TestApp.ViewControllerEditor userDragged:]未認識セレクタインスタンス0x7fc6b3c282b0に送ら'関数 'didSelectLabel()'の外に関数 'userDragged(gesture :)'を置くことはできません。そうすれば 'label.center = loc'はエラーを返します。 「ラベルが」関数の内部で呼ばれているので、これが最も簡単な方法は、didSelectLabel外にあなたの関数を移動し、それを変更することです「didSelectLabel()」

答えて

2

です:

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

} 
+0

それは動作します!!!どうもありがとうございます。私はこの間数日間苦労してきた... – edoriggio

関連する問題