Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/113.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 如何将触摸插座添加到自定义UIView?_Ios_Swift_Cocoa Touch_Uiview - Fatal编程技术网

Ios 如何将触摸插座添加到自定义UIView?

Ios 如何将触摸插座添加到自定义UIView?,ios,swift,cocoa-touch,uiview,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

我创建了以下自定义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时将其连接到函数。我该怎么做?

您必须将UIControl子类化,而不是UIView子类化

@IBDesignable
class YearSelectorSegControl: UIControl {
   ...
}
使用故事板

  • 将identity inspector上的
    ui视图
    类更改为
    ui按钮

  • 现在,您可以将该
    ui视图的操作连接设置为
    ui按钮

  • 请参阅下面的代码

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

    有什么区别?UIControl子类UIView,但xcode允许将@iActions连接到它。这可能是我正在做的事情有问题。我尝试过以编程方式添加手势并执行此操作。该函数从未被调用。我意识到我的子视图已启用userInteractiveEnabled,这意味着子视图正在获取所有事件。一旦我为所有子视图禁用了userInteractiveEnabled,这就解决了问题。如果要建立的连接是默认连接之一(即onTouchDownOutside、onTouchUpInside等),则UIControl方法会更好。在你添加手势识别器的情况下,你必须管理上下触碰,以及所有其他变量。你为什么不在故事板上尝试这个呢?@Thili77这就是我要做的