我正在尝试在自定义视图上启用UIGestureTap。我有一个视图控制器,在该视图控制器中,当我按下一个按钮时,会弹出一个自定义视图。
var transparentBackground = UIView()
@IBAction func UserViewImage(_ sender: UIButton) -> Void {
self.transparentBackground = UIView(frame: UIScreen.main.bounds)
self.transparentBackground.backgroundColor = UIColor(white: 0.0, alpha: 0.4)
UIApplication.shared.keyWindow!.addSubview(self.transparentBackground)
self.opaqueView = self.setupOpaqueView()
self.transparentBackground.addSubview(opaqueView)
UIApplication.shared.keyWindow!.bringSubview(toFront: self.transparentBackground)
self.view.bringSubview(toFront: transparentBackground)
}
我希望能够点击transparentBackground视图并将其关闭。所以我有一个名为removeAnimate()
的解雇函数 func removeAnimate()
{
UIView.animate(withDuration: 0.25, animations: {
self.transparentBackground.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.transparentBackground.alpha = 0.0;
}, completion:{(finished : Bool) in
if (finished)
{
self.transparentBackground.removeFromSuperview()
}
});
}
所以,在viewdidload中我启用了UITapGesture:
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(removeAnimate))
self.transparentBackground.addGestureRecognizer(gestureRecognizer)
self.transparentBackground.isUserInteractionEnabled = true
我知道函数removeAnimate有效,因为我在transparentBackground视图中的一个按钮上使用它,它完美地工作。但是,当我点击transparentBackground视图时,它不会消失,我不确定我做错了什么
func setupOpaqueView() -> UIView{
let mainView = UIView(frame: CGRect(x: 16, y: 132, width: Int(UIScreen.main.bounds.width-32), height: 403))
mainView.backgroundColor = UIColor.clear
mainView.layer.cornerRadius = 6
self.imageView = UIImageView(frame: CGRect(x: 29, y: 18, width: 274, height: 350))
mainView.addSubview(OKbutton)
mainView.addSubview(self.imageView)
OKbutton.addTarget(self, action: #selector(ThirdWheelViewController.handleOKButtonTapped(_:)), for: .touchUpInside)
return mainView
}
答案 0 :(得分:1)
这是一个例子,希望它可以帮助你:
首先创建一个变量:
@Component({
selector : 'child',
template : `<h2>Home</h2>
`,
})
export class childComp implements onChanges, onInit{
@Input() test1;
ngOnChanges(){
console.log(this.test1);
}
ngOnInit(){
console.log(this.test1);
}
}
这将是我们添加自定义视图的功能:
var customView:UIView!
最后:
@IBAction func customAction(_ sender: AnyObject) {
self.customView = UIView.init(frame: CGRect.init(x: self.view.bounds.width / 2, y: self.view.bounds.height / 2, width: 100, height: 100))
self.customView.backgroundColor = UIColor.red
self.view.addSubview(self.customView)
let tap = UITapGestureRecognizer.init(target: self, action: #selector(self.removeFromSuperView))
tap.numberOfTapsRequired = 1
self.customView.addGestureRecognizer(tap)
}