我是Xcode和Swift编程的新手,似乎我不懂语言。我正在尝试创建一个按钮,在单击时更改图像并弹出菜单的动画。只要我不更改图像,一切正常。一旦我添加了按钮图像的切换,动画就不会做它应该做的事情。
我的印象是当我使用'setImage'时会改变一些参数。
@IBAction func buttonMoreClicked(_ sender: UIButton) {
toggleButton(button: sender, imageOn: UIImage(named: "iconClose.png")!, imageOff: UIImage(named: "iconAdd.png")!)
if (boolFirstClickButtonMore == false) {
boolFirstClickButtonMore = true
self.centerAddEventButton = self.buttonAddEvent.center
self.centerAddGroceryButton = self.buttonAddGrocery.center
self.centerAddTasksButton = self.buttonAddTasks.center
self.righttopAddEventLabel = self.labelAddEvent.frame.origin
self.righttopAddGroceryLabel = self.labelAddGrocery.frame.origin
self.righttopAddTasksLabel = self.labelAddTasks.frame.origin
self.buttonAddEvent.center = self.buttonMore.center
self.buttonAddGrocery.center = sender.center
self.buttonAddTasks.center = sender.center
self.labelAddEvent.frame.origin = self.buttonMore.frame.origin
self.labelAddGrocery.frame.origin = self.buttonMore.frame.origin
self.labelAddTasks.frame.origin = self.buttonMore.frame.origin
}
// If button 'MORE' is set then hide menu buttons
if (boolSetMore) {
boolSetMore = false
sender.layer.backgroundColor = self.colorGreen.cgColor
UIView.animate(withDuration: 0.3, animations: {
self.buttonAddEvent.center = self.buttonMore.center
self.buttonAddGrocery.center = sender.center
self.buttonAddTasks.center = sender.center
self.labelAddEvent.frame.origin = self.buttonMore.frame.origin
self.labelAddGrocery.frame.origin = sender.frame.origin
self.labelAddTasks.frame.origin = sender.frame.origin
self.viewDisable.alpha = 0.0
self.buttonAddEvent.alpha = 0.0
self.buttonAddGrocery.alpha = 0.0
self.buttonAddTasks.alpha = 0.0
self.labelAddEvent.alpha = 0.0
self.labelAddGrocery.alpha = 0.0
self.labelAddTasks.alpha = 0.0
})
}
else {
boolSetMore = true
self.viewDisable.alpha = 0.75
self.buttonMore.layer.backgroundColor = self.colorDarkGreen.cgColor
UIView.animate(withDuration: 0.3, animations: {
self.buttonAddEvent.center = self.centerAddEventButton
self.buttonAddGrocery.center = self.centerAddGroceryButton
self.buttonAddTasks.center = self.centerAddTasksButton
self.labelAddEvent.frame.origin = self.righttopAddEventLabel
self.labelAddGrocery.frame.origin = self.righttopAddGroceryLabel
self.labelAddTasks.frame.origin = self.righttopAddTasksLabel
self.buttonAddEvent.alpha = 1.0
self.buttonAddGrocery.alpha = 1.0
self.buttonAddTasks.alpha = 1.0
self.labelAddEvent.alpha = 1.0
self.labelAddGrocery.alpha = 1.0
self.labelAddTasks.alpha = 1.0
})
}
}
func toggleButton(button: UIButton, imageOn: UIImage, imageOff: UIImage) {
if (button.currentImage == imageOn) {
button.setImage(imageOff, for: .normal )
}
else {
button.setImage(imageOn, for: .normal )
}
}
单击buttonMore时,buttonMore会显示三个按钮和标签。再次单击时,三个按钮和标签应移回buttonMore,alpha设置为0(动画)。这工作正常,但是当我添加图像的切换时,三个按钮的位置会发生变化,动画也会消失。有人有想法吗?