gpt4 book ai didi

ios - 创建不占用全屏的 UIViewController 时,如何通过点击外部来关闭它?

转载 作者:行者123 更新时间:2023-11-29 02:09:41 26 4
gpt4 key购买 nike

我正在关注this tutorial在 iOS 8 中使用 frameOfPresentedViewInContainerView 制作一个覆盖 View Controller ,但我很好奇,如何根据点击可见区域之外来关闭此 View Controller ?

最佳答案

There is one popular solution where you add a UITapGestureRecognizer to the window and then perform a hit test to check if the tap was outside the modal view frame.

但是,由于您使用的是 UIPresentationController,我建议您采用更通用的解决方案:

在您的 UIPresentationController 子类中覆盖 presentationTransitionWillBegin:

override func presentationTransitionWillBegin() {
var dimView = UIView() // Use your specific subclass here
dimView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5) // No need for this if you have your subclass defined in IB

self.containerView?.addSubview(dimView)
dimView.snp_makeConstraints { (make) -> Void in // I use SnapKit to avoid the NSLayoutConstraint nonsense
make.edges.equalTo(self.containerView!)
}
dimView.addSubview(self.presentedViewController.view)

let transitionCoordinator = self.presentedViewController.transitionCoordinator()

dimView.alpha = 0
transitionCoordinator?.animateAlongsideTransition({ (context) -> Void in
dimView.alpha = 1
}, completion: { (context) -> Void in

})
}

这将为您提供一个适当的调光 View ,该 View 将放置在您呈现的 View Controller 后面。现在完全取决于你如何处理那个变暗的 View ,你可以设置它的样式或在那里放置按钮:

enter image description here

我建议在界面构建器中定义这个 View ,这样会容易很多,示例可能如下所示:

class MyDimView: UIView {
var onPrevAction: (() -> ())?
var onNextAction: (() -> ())?
var onTapAction: (() -> ())?

@IBOutlet private var prevButton: UIButton!
@IBOutlet private var nextButton: UIButton!
@IBOutlet private var button: UIButton!

@IBAction private func onPrevButtonTouched() {
if let prevAction = self.onPrevAction {
prevAction()
}
}

@IBAction private func onNextButtonTouched() {
if let nextAction = self.onNextAction {
nextAction()
}
}

@IBAction private func onViewTouched() {
if let tapAction = self.onTapAction {
tapAction()
}
}
}

这样您就可以完全控制外部发生的事情或您呈现的 View Controller 。

关于ios - 创建不占用全屏的 UIViewController 时,如何通过点击外部来关闭它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29423704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com