如何为自定义UIView添加触摸屏?

时间:2017-09-10 20:07:12

标签: ios swift cocoa-touch uiview

我创建了以下自定义UIVIew:

//
//  YearSelectorSegControl.swift
//  OurDailyStrength iOS
//
//  Created by Rob Avery on 8/28/17.
//  Copyright © 2017 Rob Avery. All rights reserved.
//

import UIKit

@IBDesignable
class YearSelectorSegControl: UIView {

    var buttons = [UIButton]()
    var selector: UIView!
    var sv: UIStackView!

    var currentPosition: Int = 0

    @IBInspectable
    var borderWidth: CGFloat = 0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable
    var borderColor: UIColor = UIColor.clear {
        didSet {
            layer.borderColor = borderColor.cgColor
        }
    }

    @IBInspectable
    var textColor: UIColor = .lightGray {
        didSet {
            updateView()
        }
    }

    @IBInspectable
    var textBackground: UIColor = .clear {
        didSet {
            updateView()
        }
    }

    func updateView() {
        // ... code here ...
    }

    override func draw(_ rect: CGRect) {
        layer.cornerRadius = 0
    }
}

当我进入Interface Builder并尝试将此UIView连接到控制器时,唯一允许的是插座。我希望能够在触摸时将这个自定义UIView连接到一个函数。我该怎么做?

2 个答案:

答案 0 :(得分:1)

您必须继承UIControl而不是UIView

@IBDesignable
class YearSelectorSegControl: UIControl {
   ...
}

答案 1 :(得分:0)

使用故事板,

  1. 将身份检查员UIView的班级更改为UIButton

  2. 现在,您可以将UIView的操作连接设置为UIButton

  3. enter image description here

    见下面的代码

    @IBAction func clickView(_ sender: UIButton) {
    
        //perform your actions in here
    
    }