2017-07-31 101 views
0

我正在创建一个按钮编程和CGAffineTransform不起作用在我的项目中,当添加在addTarget,为什么?Swift 3 - CGAffineTransform不起作用

编辑:

func createButtonPuzzle(id: Int) { 

    for i in 1...14 { 

      let btnButton = UIButton(type: .roundedRect) 
      btnButton.frame = CGRect(x: self.view.frame.size.width/2, y: self.view.frame.size.height/2, width: 100, height: 100) 
      btnButton.backgroundColor = .blue 
      btnButton.setTitle("iButton", for: .normal) 
      btnButton.addTarget(self, action: #selector(moveButton(sender:)), for: .touchUpInside) 

      view.addSubview(btnButton) 
    } 
} 


func moveButton(sender: UIButton) { 

    if sender.tag == 1 { 

     if sender.transform == CGAffineTransform.identity { 

      UIView.animate(withDuration: 0.5, animations: 
      sender.transform = CGAffineTransform(translationX: 50, y: 100) 

      }) 
     }     
    } 
} 
+0

是使用自动布局或自动尺寸定位的看法?这可能不适用于自动布局。 – Sulthan

+0

不使用自动布局或自动调整,它已经工作,但现在不起作用! @Sulthan –

+0

你有没有设置断点?你知道它是否真的达到了转变?为什么你需要'moveButton'的参数名? – dfd

回答

1

在功能上,而不是使用sender.transform,使用btnButton.transform,因为你是超出范围,这是造成的,发件人可能被解雇,这将导致动画来解雇。

另一种选择是牢固地保持对象:

let tappedButton : UIButton = sender 

然后用tappedButton

编辑

我的意思是这样的:

func moveButton(sender: UIButton) { 

    if ((sender.tag == 1) && (sender == self.btnButton)) { 

     if self.btnButton.transform == CGAffineTransform.identity { 

      UIView.animate(withDuration: 0.5, animations: 
       self.btnButton.transform = CGAffineTransform(translationX: 50, y: 100) 

      }) 
     }     
    } 
} 

ED IT - 2

根据你的代码有2个问题:

  1. 所有14个按钮在另一个顶部堆叠1,这意味着按钮14将最上面的按钮,而不是按钮1
  2. 您没有设置标签,然后在你的支票moveButton失败:

    FUNC createButtonPuzzle(ID:智力){

    for i in 1...14 { 
    
         let btnButton = UIButton(type: .roundedRect) 
         btnButton.frame = CGRect(x: self.view.frame.size.width/2, y: self.view.frame.size.height/2, width: 100, height: 100) 
         btnButton.backgroundColor = .blue 
         btnButton.setTitle("iButton", for: .normal) 
         btnButton.addTarget(self, action: #selector(moveButton(sender:)), for: .touchUpInside) 
    
         **btnButton.tag = i // This is missing ** 
    
         view.addSubview(btnButton) 
    } 
    

    }

然后失败: 如果sender.tag == 1 {

所以对它进行测试,看看它的工作,首先你需要要么去从14到1并从1 .. < 2或将按钮重新放置在不同的位置,以便它实际上可以工作。

然后将这些代码会被设置在与标签1按钮将被挖掘,将工作

+0

我在另一个函数中创建了btnButton,并且我在btnButton @unkgd中添加了这个函数 –

+0

您是否检查过实际上是否获得了动画?作为@dfd建议?如果你确实到了那里,并且一切似乎都没问题,那么将你的按钮作为数据成员添加到控制器中,并使用该引用,因为这意味着它被忽略,因为它有一个弱引用。 – unkgd

+0

是的,我检查了,我添加数据到控制器,一切似乎OK @loggd –