gpt4 book ai didi

swift - 在覆盖 View 上启用用户交互

转载 作者:行者123 更新时间:2023-11-30 10:48:41 25 4
gpt4 key购买 nike

我正在 UITableView 顶部创建一个变暗的覆盖层,我想突出显示其中一行。我可以突出显示它,但如何启用用户交互(例如点击单元格)?

func addFullScreenDarkOverlay(){
let viewDarkOverlay = UIView()
viewDarkOverlay.alpha = 0.5
viewDarkOverlay.backgroundColor = .black
viewDarkOverlay.frame = UIApplication.shared.keyWindow!.frame

// add dummy hole (will change it to the frame of the particular cell)
let holeFrame = CGRect(x: 0, y: 0, width: viewDarkOverlay.frame.width/2, height: viewDarkOverlay.frame.height/2)

// Do any additional setup after loading the view.
let path = CGMutablePath()
// Dark background
path.addRect(CGRect(x: 0, y: 0, width: viewDarkOverlay.frame.width, height: viewDarkOverlay.frame.height))
// White/spotlight path
path.addRect(holeFrame)

let maskLayer = CAShapeLayer()
maskLayer.backgroundColor = UIColor.black.cgColor
maskLayer.path = path;
maskLayer.fillRule = kCAFillRuleEvenOdd

viewDarkOverlay.layer.mask = maskLayer
viewDarkOverlay.clipsToBounds = true


UIApplication.shared.keyWindow!.addSubview(viewDarkOverlay)


}

最佳答案

基本上,您可以禁用 mask View 的用户交互,这会将所有触摸事件传递到下面的 View ...但是,如果您只是希望突出显示的区域难以处理(即单元格),您可以可以创建一个自定义的 UIView 子类,重写 hitTest 方法,如下所示:

import UIKit

class MaskView: UIView {

var hitableArea: CGRect {
return CGRect(x: 0, y: 0, width: bounds.width * 0.5, height: bounds.height * 0.5)
}

override init(frame: CGRect) {
super.init(frame: frame)
installMaskLayer()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
installMaskLayer()
}

private func installMaskLayer() {

backgroundColor = UIColor.black.withAlphaComponent(0.5)

let path = CGMutablePath()
// Dark background
path.addRect(bounds)
// White/spotlight path
path.addRect(hitableArea)

let maskLayer = CAShapeLayer()
maskLayer.backgroundColor = UIColor.black.cgColor
maskLayer.path = path;
maskLayer.fillRule = CAShapeLayerFillRule.evenOdd

layer.mask = maskLayer
}

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if (!self.isUserInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
return nil;
}

if (hitableArea.contains(point)) {
return nil
}

return self
}
}

只需创建此自定义 View 并将其添加到您的窗口中,现在您只能触摸该单元格。

关于swift - 在覆盖 View 上启用用户交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55159092/

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