简体   繁体   中英

How do you add touch outlets to custom UIView?

I've created the following custom 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
    }
}

When I go to the Interface Builder, and try and connect this UIView to the controller, the only thing allowed is an outlet. I want to be able to connect this custom UIView to a function when it's touched. How do I do that?

You have to subclass UIControl instead of UIView

@IBDesignable
class YearSelectorSegControl: UIControl {
   ...
}

Using storyboard,

  1. Change the class of UIView on identity inspector as UIButton

  2. Now you can set action connection to that UIView as UIButton

在此处输入图片说明

See below code

@IBAction func clickView(_ sender: UIButton) {

    //perform your actions in here

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM