为未被调用的UIButton添加目标

时间:2016-02-23 14:15:01

标签: ios swift uibutton

我最近发布了一篇类似的帖子,我发现了问题所在,但我不知道如何解决这个问题。

在我的ImageViewerViewController中,我的cancelButtonTapped函数未被调用。但我不认为这个问题必然存在于这段代码中。这是代码:

var image: UIImage!
var imageView: UIImageView!
var scrollView: UIScrollView!
var disableSavingImage: Bool!
var pan: UIPanGestureRecognizer!
var cancelButton: UIButton!
var cancelButtonImage: UIImage!

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.0)
    setCancelButton()

}

func setCancelButton() {

    self.cancelButton = UIButton(type: UIButtonType.RoundedRect)
    self.cancelButton.addTarget(self, action: "cancelButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
    self.cancelButton.setImage(cancelButtonImage, forState: UIControlState.Normal)
    self.cancelButton.tintColor = UIColor.whiteColor()
    self.cancelButton.frame = CGRectMake(self.view.frame.size.width - (self.cancelButtonImage.size.width * 2) - 18, 18, self.cancelButtonImage.size.width * 2, self.cancelButtonImage.size.height * 2)
    self.view.addSubview(self.cancelButton)

}

func cancelButtonTapped(sender: UIButton) {

    print("cancelButtonTapped")

}

func centerPictureFromPoint(point: CGPoint, ofSize size: CGSize, withCornerRadius radius: CGFloat) {

    UIView.animateWithDuration(0.3, animations: { () -> Void in
        self.view.backgroundColor = UIColor(colorLiteralRed: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)

        }) { (finished: Bool) -> Void in

    }

}

我认为问题在于CathyTaskLogMessageViewController,当我更改代码时 self.view.addSubview(imageViewerViewController.view)self.presentViewController(imageViewerViewController, animated: true, completion: nil),我的添加目标函数被调用。这是代码:

    func defaultPictureButtonTapped(sender: UIButton) {

        let imageViewerViewController = ImageViewerViewController()
        imageViewerViewController.image = self.defaultPictureButton.imageView!.image
        imageViewerViewController.cancelButtonImage = UIImage(named: "cancelButtonImage")
        self.view.addSubview(imageViewerViewController.view)
        imageViewerViewController.centerPictureFromPoint(self.defaultPictureButton.frame.origin, ofSize: self.defaultPictureButton.frame.size, withCornerRadius: self.defaultPictureButton.layer.cornerRadius)
//        self.presentViewController(imageViewerViewController, animated: true, completion: nil)

    }

但是,我不想呈现一个视图控制器。我想将其添加为子视图。有人有任何想法解决这个问题吗?非常感谢你的帮助。

2 个答案:

答案 0 :(得分:2)

问题在于如何添加子视图控制器。 您需要在addChildViewController(imageViewerViewController)

之前致电self.view.addSubview(imageViewerViewController.view)

答案 1 :(得分:0)

在使用子视图时发生的事情是,视图位于子视图前面,因此子视图上的按钮没有被轻敲。

试试这个: -

imageViewerViewController.view.layer.zPosition = 2
//You can set any value in place of 2 which is greater than zposition value of the view
self.view.addSubview(imageViewerViewController.view)

希望这有效。