在视图控制器中与自定义UIView进行交互

时间:2019-02-25 10:04:32

标签: ios swift uiview

我创建了一个UIView,要显示在我的视图控制器中。我已经创建了UIView并与其他UI组件一起显示,但是我现在遇到的问题是我不能与UIView上的元素交互。

下面是我的代码

class SliderView: CustomView {

    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var sliderImage: UIImageView!
    @IBOutlet weak var sliderText: UILabel!

    override func initialize() {
        super.initialize()

        let name = String(describing: type(of: self))
        let nib = UINib(nibName: name, bundle: .main)
        nib.instantiate(withOwner: self, options: nil)

        self.addSubview(self.containerView)
        self.containerView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.containerView.topAnchor.constraint(equalTo: self.topAnchor),
            self.containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            self.containerView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
            ])
    }

    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        return sliderImage.frame.contains(point)
    }

@IBAction func clickme(_ sender: UIButton) {
    print("SWIPPERD minmax22g")
}

}

在视图控制器中

weak var sliderView: SliderView!

    override func loadView() {
        super.loadView()

        let sliderView = SliderView()
        self.view.addSubview(sliderView)
        NSLayoutConstraint.activate([
            sliderView.topAnchor.constraint(equalTo: self.view.topAnchor),
            sliderView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            sliderView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
            ])
        self.sliderView = sliderView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        sliderView.sliderText.text = "HOOOOO WORKS"
}

1 个答案:

答案 0 :(得分:0)

1-您不应在自定义视图内再次添加插座作为子视图

@IBOutlet weak var containerView: UIView!
self.addSubview(self.containerView)

添加此方法并使用它来获取实例

static func getInstance() -> SliderView { 
   return Bundle.main.loadNibNamed("SliderView", owner: self, options: nil)![0] as! SliderView
}

2-这将使imageView成为视图内唯一的活动帧

return sliderImage.frame.contains(point)

3-不要在loadView内添加子视图,而在viewDidLoad内添加子视图

let sliderView = SliderView()

let sliderView = SliderView.getInstance()