Rob Avery IV
Rob Avery IV

Reputation: 3740

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?

Upvotes: 0

Views: 766

Answers (2)

Thili77
Thili77

Reputation: 1095

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

enter image description here

See below code

@IBAction func clickView(_ sender: UIButton) {

    //perform your actions in here

}

Upvotes: -1

hfehrmann
hfehrmann

Reputation: 457

You have to subclass UIControl instead of UIView

@IBDesignable
class YearSelectorSegControl: UIControl {
   ...
}

Upvotes: 1

Related Questions