【问题标题】:How do you add touch outlets to custom UIView?如何将触摸插座添加到自定义 UIView?
【发布时间】:2018-02-19 01:39:27
【问题描述】:

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

【问题讨论】:

  • 你为什么不在故事板上试试这个?
  • @Thili77 这就是我想要做的

标签: ios swift cocoa-touch uiview


【解决方案1】:

使用故事板,

  1. 将身份检查器上UIView的类更改为UIButton

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

见下面的代码

@IBAction func clickView(_ sender: UIButton) {

    //perform your actions in here

}

【讨论】:

    【解决方案2】:

    你必须继承 UIControl 而不是 UIView

    @IBDesignable
    class YearSelectorSegControl: UIControl {
       ...
    }
    

    【讨论】:

    • 有什么区别?
    • UIControl 子类 UIView,但 xcode 允许将 @IBActions 连接到它。
    • 我正在做的事情可能有问题。我尝试以编程方式添加手势并执行此操作。该函数永远不会被调用。
    • 我意识到我有带有 userInteractiveEnabled 的子视图,这意味着子视图正在获取所有事件。一旦我为所有子视图禁用了 userInteractiveEnabled,就解决了。
    • 如果您要建立的连接是默认连接之一(即 onTouchDownOutside、onTouchUpInside 等),那么 UIControl 方法会更好。在添加手势识别器的情况下,您必须管理 touch down 和 up 以及所有其他变量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 2019-10-24
    相关资源
    最近更新 更多