【问题标题】:Button action is not working on subView按钮操作不适用于 subView
【发布时间】:2017-07-10 12:49:54
【问题描述】:

在我的一个 iOS 项目中,我以编程方式在我的 Feed ViewController(主视图)上添加了 Filter ViewController(子视图)的子视图。

Filter ViewController 上有几个按钮可以选择价格、城市等。

插座已连接,但当我尝试拍摄按钮动作时,它无法正常工作。 我也启用了 isUserInteractionEnabled 但仍然无法正常工作。

累加。对我来说,这与视图上的子视图有关!但要解决这个问题。你能建议我如何拍摄子视图的按钮动作吗?

class FilterViewController: BaseUIViewController{

   override func viewWillAppear(_ animated: Bool) {
     super.viewWillAppear(animated)

     cityButton.isUserInteractionEnabled = true
   }

   @IBAction func selectCity(_ sender: Any)
   {
    print("selectCity action")
   }
}

【问题讨论】:

  • 请发布您的代码并让我们知道您已经尝试过什么,然后我们才能为您提供帮助
  • 在将视图控制器添加为另一个视图控制器中的子视图时,请记住使用 add childViewController 方法。在你的情况下是feedViewController.addChildViewController(childController: filterViewController)
  • @DatForis 好的。我会尝试。感谢您的回复。
  • 检查您的按钮是否超出框架
  • @HarshalValanda 好的。谢谢你。我会检查

标签: ios swift button filtering subview


【解决方案1】:

使用下面的代码将您的 FilterViewController 作为子视图添加到您的 ViewController

filterViewController.willMove(toParentViewController: self)
self.view.addSubview(filterViewController.view)
self.addChildViewController(filterViewController)
filterViewController.didMove(toParentViewController: self)

【讨论】:

  • @dedicatedcoder : 很高兴能帮上忙 :) 编码愉快
  • @xhinoda :很高兴我能帮上忙 :)
  • 对于其他任何需要此解决方案的人。你需要 self.addChildViewController(filterViewController.init())
【解决方案2】:

@SandeepBhandari 解决方案对于类似问题仍然有效。

这些UIViewController 扩展将很有用。

extension UIViewController {

func add(asChildViewController viewController: UIViewController, containerView: UIView) {
    addChild(viewController)
    containerView.addSubview(viewController.view)
    viewController.view.frame = containerView.bounds
    viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    viewController.didMove(toParent: self)
}

func remove(asChildViewController viewController: UIViewController) {
    viewController.willMove(toParent: nil)
    viewController.view.removeFromSuperview()
    viewController.removeFromParent()
} 

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-24
    • 2013-04-28
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    相关资源
    最近更新 更多