Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 自定义视图按钮单击它';它不工作了_Ios_Swift - Fatal编程技术网

Ios 自定义视图按钮单击它';它不工作了

Ios 自定义视图按钮单击它';它不工作了,ios,swift,Ios,Swift,这是我的密码 我通过在xib中定义视图来注册按钮操作。 btn已连接到dismissButtonClick,但当我单击该按钮时,它不起作用。 因此,我尝试了一种方法来覆盖触摸功能,但它不起作用 我的第三次尝试是手势注册。 它也不起作用 我再也没有办法了 请帮帮我,伙计们 @objc public class CustomView : UIView { static let xibName = "xibName" @IBOutlet weak var mainView: UIV

这是我的密码

我通过在xib中定义视图来注册按钮操作。 btn已连接到dismissButtonClick,但当我单击该按钮时,它不起作用。 因此,我尝试了一种方法来覆盖触摸功能,但它不起作用

我的第三次尝试是手势注册。 它也不起作用

我再也没有办法了

请帮帮我,伙计们

@objc public class CustomView : UIView  {
    static let xibName = "xibName"

    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var viewTopAnchor: NSLayoutConstraint?
    @IBOutlet weak var btn: UIButton?
    var completion: (() -> Void)?

    var parentView : UIViewController!

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

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

    public static func getInstance(_ vc : UIViewController, _ completion : (() -> Void)? ) -> UIView {

        let view = Bundle.main.loadNibNamed(CustomView.xibName, owner: self, options: nil)?.first as! CustomView

        view.parentView = vc
        view.completion = completion

        view.initUI()

        return view
    }

    func initUI() {

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(CustomView.dismiss))
        mainView.addGestureRecognizer(tapGestureRecognizer)

        btn?.addTarget(self, action: #selector(CustomView.dismiss), for: .touchUpInside)


        parentView.view.addSubview(self)

        self.translatesAutoresizingMaskIntoConstraints = false

        self.leadingAnchor.constraint(equalTo: parentView.view.leadingAnchor, constant: 0).isActive = true
        self.trailingAnchor.constraint(equalTo: parentView.view.trailingAnchor, constant: 0).isActive = true
        viewTopAnchor?.constant = -150
        viewTopAnchor?.isActive = true

        setNeedsDisplay()
        layoutIfNeeded()

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5 ) {
            self.mainView.isHidden = false
            self.showAnimation()
        }
}


    //top down anim
    private func showAnimation(){
        DispatchQueue.main.asyncAfter(deadline: .now() ) {
            self.viewTopAnchor?.constant = 0
            UIView.animate(withDuration: 0.5) {
                self.layoutIfNeeded()
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    self.dismissAnimation(self.duration)
                }
            }
        }
    }


    private func dismissAnimation(_ duration : Double){
        DispatchQueue.main.asyncAfter(deadline: .now() + duration - 0.5) {

            self.viewTopAnchor?.constant = -150
            UIView.animate(withDuration: 1) {
                self.layoutIfNeeded()
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    self.completion?()
                    self.removeFromSuperview()
                }
            }
        }
    }

    public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("touchBegan") // not called
        let touch = touches.first
    }

    public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("touchBegan") // not called
        self.completion?()
        self.btn?.removeTarget(self, action: #selector(dismissButtonClick), for: .touchUpInside)
        self.removeFromSuperview()
    }

    @objc
    func dismiss(){
        print("dismiss") // not called
        self.completion?()
        self.removeFromSuperview()
    }
    @IBAction func dismissButtonClick(_ sender: Any) {
        print("dismissButtonClick") // not called
        self.completion?()
        self.removeFromSuperview()
    }

}

我用一个按钮创建了一个自定义视图,并编写了一个在单击按钮时调用的方法。请检查一下,对你的情况可能会有帮助。
https://github.com/bhoomik/Custom_View_Demo 
自定义视图代码
//
//斯威夫特
//临时工
//
//Jaimin Modi于20年2月19日创建。
//版权所有©2020 Jaimin Modi。版权所有。
//
导入UIKit
//
//斯威夫特
//临时工
//
//
导入UIKit
类CustomView:UIView{
static name=“CustomView”
@IBOutlet弱var viewTopAnchor:NSLayoutConstraint?
@IBOUTLE弱var btn:UIButton?
var完成:(()->无效)?
var parentView:UIViewController!
重写初始化(帧:CGRect){
super.init(frame:frame)
}
必需的初始化?(编码器aDecoder:NSCoder){
super.init(编码者:aDecoder)
}
公共静态函数getInstance(vc:UIViewController,UCompletion:(()->Void)?)->UIView{
让view=Bundle.main.loadNibNamed(CustomView.name,所有者:self,选项:nil)?。首先是!CustomView
view.parentView=vc
view.completion=完成
//view.frame=CGRect(x:0,y:0,宽度:UIScreen.main.bounds.size.width,高度:120)
view.initUI()
返回视图
}
func initUI(){
//让tapGestureRecognizer=UITapGestureRecognizer(目标:自我,操作:#选择器(CustomView.Dislose))
//mainView.addGestureRecognizer(tapGestureRecognizer)
//btn?.addTarget(self,action:#选择器(CustomView.disclose),for:.touchUpInside)
parentView.view.addSubview(自)
self.translatesAutoResizengMaskintoConstraints=false
//self.leadingAnchor.constraint(equalTo:parentView.view.leadingAnchor,常量:0)。isActive=true
//self.trailingAnchor.constraint(equalTo:parentView.view.trailingAnchor,常量:0)。isActive=true
//viewTopAnchor?常数=-150
//viewTopAnchor?常数=300
//viewTopAnchor?.isActive=true
let guide=self.parentView.view.safeAreaLayoutGuide
NSLayoutConstraint.activate(
[self.leftAnchor.constraint(equalTo:self.parentView.view.leftAnchor),
自高度锚定约束(等恒量:50),
self.rightAnchor.constraint(等式:self.parentView.view.rightAnchor),
//segmentedControl!.topAnchor.constraint(等式:view.topAnchor,常量:80)]
self.topAnchor.constraint(等式:guide.topAnchor,常量:0)]
)
setNeedsDisplay()
layoutIfNeeded()
/*DispatchQueue.main.asyncAfter(截止日期:.now()+0.5){
self.mainView.ishiden=false
self.showAnimation()
}*/
}
@iAction func dismissButtonClick(\发送方:任意){
打印(“dismissButtonClick”)//未调用
//自我完成?()
//self.removeFromSuperview()
}
/*
//仅当执行自定义绘图时才重写绘图()。
//空实现会对动画期间的性能产生不利影响。
重写函数绘图(rect:CGRect){
//绘图代码
}
*/
}
UIView控制器代码
:
导入UIKit
扩展UIView{
类func fromNib()->T{
返回捆绑包(用于:T.self)。loadNibNamed(字符串(描述:T.self),所有者:nil,选项:nil)![0]为!T
}
}
类ViewController:UIViewController{
@IBVAR viewNav:CustomView!
var完成:(()->无效)?
重写func viewDidLoad(){
super.viewDidLoad()
/*viewNav=UIView.fromNib()
viewNav.frame=CGRect(x:0,y:0,宽度:self.view.frame.size.width,高度:viewNav.frame.size.height)
self.view.addSubview(视图导航)*/
getInstance(self,completion)
//加载视图后执行任何其他设置。
}
/*
//标记:-导航
//在基于故事板的应用程序中,您通常需要在导航之前做一些准备
覆盖功能准备(对于segue:UIStoryboardSegue,发送方:有吗?){
//使用segue.destination获取新的视图控制器。
//将选定对象传递给新的视图控制器。
}
*/
}
[1]: https://github.com/bhoomik/Custom_View_Demo

请检查您在Xib中的视图层次结构,并确保您的按钮位于所有视图的顶部。@shraddha11“是”按钮位于所有视图的顶部…确定。您能否展示或解释一下您是如何将按钮连接到操作的?您使用哪个事件连接?@shraddha11谢谢您的帮助!我编辑了这篇文章。@Sean你使用NavigationBar吗?@Sean我试图根据我的代码修改我的代码。但我并没有得到任何意见,在家长根据您的约束,因为我并没有完整的代码。所以,我改变了约束条件。请检查可能对您有帮助
CustomView.getInstance(view, completion)
    I have created one custom view with one button and wrote method which is called on button click. Please check it out it might be helpful in your case.

https://github.com/bhoomik/Custom_View_Demo 

    Custom View Code


    //
    //  CustomView.swift
    //  Temp
    //
    //  Created by Jaimin Modi on 19/02/20.
    //  Copyright © 2020 Jaimin Modi. All rights reserved.
    //

        import UIKit

    //
//  CustomView.swift
//  Temp
//
//

import UIKit

class CustomView: UIView {


    static let xibName = "CustomView"

    @IBOutlet weak var viewTopAnchor: NSLayoutConstraint?
    @IBOutlet weak var btn: UIButton?
    var completion: (() -> Void)?

    var parentView : UIViewController!

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

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

    public static func getInstance(_ vc : UIViewController, _ completion : (() -> Void)? ) -> UIView {

        let view = Bundle.main.loadNibNamed(CustomView.xibName, owner: self, options: nil)?.first as! CustomView
        view.parentView = vc
        view.completion = completion
       // view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 120)
        view.initUI()

        return view
    }


    func initUI() {

      //  let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(CustomView.dismiss))
       // mainView.addGestureRecognizer(tapGestureRecognizer)

        //btn?.addTarget(self, action: #selector(CustomView.dismiss), for: .touchUpInside)


        parentView.view.addSubview(self)

        self.translatesAutoresizingMaskIntoConstraints = false

       // self.leadingAnchor.constraint(equalTo: parentView.view.leadingAnchor, constant: 0).isActive = true
      //  self.trailingAnchor.constraint(equalTo: parentView.view.trailingAnchor, constant: 0).isActive = true
     //   viewTopAnchor?.constant = -150

     //   viewTopAnchor?.constant = 300
      //  viewTopAnchor?.isActive = true



        let guide = self.parentView.view.safeAreaLayoutGuide

        NSLayoutConstraint.activate(
            [self.leftAnchor.constraint(equalTo: self.parentView.view.leftAnchor),
             self.heightAnchor.constraint(equalToConstant: 50),
             self.rightAnchor.constraint(equalTo: self.parentView.view.rightAnchor),
             // segmentedControl!.topAnchor.constraint(equalTo: view.topAnchor, constant: 80)]
                self.topAnchor.constraint(equalTo: guide.topAnchor, constant: 0)]


        )

        setNeedsDisplay()
        layoutIfNeeded()

       /* DispatchQueue.main.asyncAfter(deadline: .now() + 0.5 ) {
            self.mainView.isHidden = false
            self.showAnimation()
        }*/

    }

    @IBAction func dismissButtonClick(_ sender: Any) {
        print("dismissButtonClick") // not called
       // self.completion?()
       // self.removeFromSuperview()
    }

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}

    UIView Controller code
    :


        import UIKit


        extension UIView {
            class func fromNib<T: UIView>() -> T {
                return Bundle(for: T.self).loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T
            }
        }

class ViewController: UIViewController {


    @IBOutlet weak var viewNav :  CustomView!

    var completion: (() -> Void)?


    override func viewDidLoad() {
        super.viewDidLoad()


        /*viewNav  = UIView.fromNib()
        viewNav.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: viewNav.frame.size.height)

        self.view.addSubview(viewNav)*/


        CustomView.getInstance(self, completion)


        // Do any additional setup after loading the view.
    }




    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

  [1]: https://github.com/bhoomik/Custom_View_Demo