屏幕外UIButton操作未触发 - iOS

时间:2016-07-10 22:28:56

标签: ios swift uibutton addtarget

我在屏幕上创建了两个UIButton,当按下按钮时,屏幕上会显示动画。但是,从不调用按钮的目标函数,因为我认为按钮没有被按下"。如果我只是在屏幕上创建按钮,按钮确实有效,所以我认为这个问题与从屏幕边界外部动画到屏幕上的按钮有关。

编辑:按钮会在屏幕上正确显示动画并且可见,但按下它们不会执行任何操作。

代码:

var isMenuOpen : Bool = false
var button_height : CGFloat = UIScreen.mainScreen().bounds.height/8

var button_view : UIView!
var mylists : UIButton!
var settings : UIButton!

@IBAction func openMenu(sender: AnyObject) {
    UIView.animateWithDuration(0.6, delay: 0.0, options: .CurveEaseOut, animations: {
        self.view.transform = CGAffineTransformMakeTranslation(0.0, self.button_height * (self.isMenuOpen ? 0 : -1))
    }, completion: {finished in
        self.isMenuOpen = !self.isMenuOpen
    })

}

override func viewDidLoad() {
    super.viewDidLoad()
    initButtons()  
}

func initButtons() {
    button_view = UIView(frame: CGRect(x:0.0, y:UIScreen.mainScreen().bounds.height, width:UIScreen.mainScreen().bounds.width, height:button_height))
    button_view.userInteractionEnabled = true

    mylists = UIButton(frame: CGRect(x:0.0, y:0.0, width:UIScreen.mainScreen().bounds.width/2.0, height:button_height))
    mylists.setTitle("My Lists", forState: .Normal)
    mylists.backgroundColor = UIColor(red: 255/255, green: 105/255, blue: 180/255, alpha: 1.0)
    mylists.addTarget(self, action: #selector(showLists(_:)), forControlEvents: .TouchUpInside)
    button_view.addSubview(mylists)

    settings = UIButton(frame: CGRect(x:UIScreen.mainScreen().bounds.width/2.0, y:0.0, width:UIScreen.mainScreen().bounds.width/2.0, height:button_height))
    settings.setTitle("Settings", forState: .Normal)
    settings.backgroundColor = UIColor(red: 135/255, green: 205/255, blue: 236/255, alpha: 1.0)
    settings.addTarget(self, action: #selector(showSettings(_:)), forControlEvents: .TouchUpInside)
    button_view.addSubview(settings)

    self.view.addSubview(button_view)
}

func showLists(sender: UIButton!) {
    print("showLists")
}

func showSettings(sender: UIButton!) {
    print("showSettings")
}

感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

我没有确切过渡的目标,但看起来按住button_view按钮的视图永远不会转移到屏幕上。

您是要尝试让每个按钮进入屏幕,还是试图让两个按钮都进入容器内的屏幕(button_view_)?如果你想两者兼顾,我建议你做

UIView.animateWithDuration(0.6, delay: 0.0, options: .CurveEaseOut, animations: {
    self.button_view.transform = CGAffineTransformMakeTranslation(0.0, -1*(UIScreen.mainScreen().bounds.height))
}, completion: {finished in
    self.isMenuOpen = !self.isMenuOpen
})

这是基于您尝试将整个框移动到整个屏幕的假设。

编辑:

啊!我看到发生了什么!所以你正在移动self.view,你永远不想移动UIViewController.view。移动视图的容器。因此,不要移动self.view,而是移动button_view。移动UIController.view会删除UIViewController的所有下层和功能