创建自定义 xib class 的实例使手势识别器不起作用
create instance of custom xib class make gesture recognizer don't work
首先我创建了一个 .xib 文件并将其命名为 RadioBtnView 并将其连接到自定义 UIView class :
class CheckBtnView: UIView {
@IBOutlet weak var mainView: UIView!
@IBOutlet weak var CheckBtn: UIButton!
@IBOutlet weak var checkDescription: UILabel!
var status = false {
didSet {
if status {
CheckBtn.backgroundColor = .orange
} else {
CheckBtn.backgroundColor = .clear
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupViews()
}
private func setupViews(){
Bundle.main.loadNibNamed("CheckBtnView", owner: self, options: nil)
addSubview(mainView)
mainView.frame = self.bounds
mainView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
}
}
然后尝试在 viewController 中以编程方式添加 RadioBtnView 实例并向其添加手势识别器:
let radio = RadioBtnView()
scrollContainerView.addSubview(radio)
radio.translatesAutoresizingMaskIntoConstraints = false
radio.topAnchor.constraint(equalTo: entry.bottomAnchor, constant: 15).isActive = true
radio.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 38).isActive = true
radio.isUserInteractionEnabled = true
let radioGesture = UITapGestureRecognizer(target: self, action: #selector(change(_:)))
radio.addGestureRecognizer(radioGesture)
但是 change(_:) 函数没有响应,好像它没有调用
这是为了以编程方式创建 xib 视图还是其他?
我终于知道原因了...我只是删除了 radio.translatesAutoresizingMaskIntoConstraints = false
并添加了 radio.frame = CGRect(x:50,y:100,width:120,height:20)
并且每个想法都有效
这似乎我们无法以编程方式添加 xib 视图
首先我创建了一个 .xib 文件并将其命名为 RadioBtnView 并将其连接到自定义 UIView class :
class CheckBtnView: UIView {
@IBOutlet weak var mainView: UIView!
@IBOutlet weak var CheckBtn: UIButton!
@IBOutlet weak var checkDescription: UILabel!
var status = false {
didSet {
if status {
CheckBtn.backgroundColor = .orange
} else {
CheckBtn.backgroundColor = .clear
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupViews()
}
private func setupViews(){
Bundle.main.loadNibNamed("CheckBtnView", owner: self, options: nil)
addSubview(mainView)
mainView.frame = self.bounds
mainView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
}
}
然后尝试在 viewController 中以编程方式添加 RadioBtnView 实例并向其添加手势识别器:
let radio = RadioBtnView()
scrollContainerView.addSubview(radio)
radio.translatesAutoresizingMaskIntoConstraints = false
radio.topAnchor.constraint(equalTo: entry.bottomAnchor, constant: 15).isActive = true
radio.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 38).isActive = true
radio.isUserInteractionEnabled = true
let radioGesture = UITapGestureRecognizer(target: self, action: #selector(change(_:)))
radio.addGestureRecognizer(radioGesture)
但是 change(_:) 函数没有响应,好像它没有调用
这是为了以编程方式创建 xib 视图还是其他?
我终于知道原因了...我只是删除了 radio.translatesAutoresizingMaskIntoConstraints = false
并添加了 radio.frame = CGRect(x:50,y:100,width:120,height:20)
并且每个想法都有效
这似乎我们无法以编程方式添加 xib 视图