我是一名Web开发人员,是iOS编程的新手。
我有两个文件。 ViewController.swift
和FilterList.swift
。当我点击Commend + R
时,模拟器出现了,样式似乎正确。但是,单击FilterList
的实例视图不会显示任何内容。
我该如何工作?我只想在一个视图中拥有一个UI组件及其事件。类似于当前的前端开发,例如React和Vue。还是有一些首选的方法来解决这个问题?ViewController.swift
:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let kindsList = FilterList()
view.isUserInteractionEnabled = true
view.backgroundColor = .blue
kindsList.handleTapGesture = {(sender: UITapGestureRecognizer ) -> Void in
print("In UIViewController")
}
view.addSubview(kindsList)
}
}
FilterList.swift
:import UIKit
class FilterList: UIView {
private let titleBarStackView = UIStackView()
private let titleBarImage = UIImage(systemName: "chevron.right", withConfiguration: UIImage.SymbolConfiguration(pointSize: 16, weight: .regular, scale: .medium))
private let titleBarImageView = UIImageView()
private let titleBarLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 160, height: 28))
// MARK:- Styles
private let spacing: CGFloat = 16.0
var labelText = "title"
var handleTapGesture: ((UITapGestureRecognizer) -> Void)?
convenience init(label: String) {
self.init()
self.labelText = label
// Tap Gesture
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap))
titleBarStackView.addGestureRecognizer(tap)
titleBarStackView.isUserInteractionEnabled = true
self.isUserInteractionEnabled = true
}
override func layoutSubviews() {
super.layoutSubviews()
// Do any additional setup after loading the view.
// Configure Arrow
titleBarImageView.image = titleBarImage
// Configure Label
titleBarLabel.text = labelText
titleBarLabel.font = UIFont.preferredFont(forTextStyle: .headline)
titleBarStackView.addArrangedSubview(titleBarLabel)
titleBarStackView.addArrangedSubview(titleBarImageView)
self.addSubview(titleBarStackView)
setupConstraints()
}
private func setupConstraints() {
titleBarStackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleBarStackView.leadingAnchor.constraint(equalTo: self.superview!.safeAreaLayoutGuide.leadingAnchor, constant: spacing),
titleBarStackView.trailingAnchor.constraint(equalTo: self.superview!.safeAreaLayoutGuide.trailingAnchor, constant: -spacing),
titleBarStackView.topAnchor.constraint(equalTo: self.superview!.safeAreaLayoutGuide.topAnchor, constant: spacing),
])
}
@objc func handleTap(_ sender: UITapGestureRecognizer) {
print("IN UIView")
self.handleTapGesture?(sender)
}
}
最佳答案
您需要使用初始化程序来为stackView设置点击手势,即FilterList(label:
。并为FilterList
提供大小,使其具有可触摸的区域。更新如下
let kindsList = FilterList(label: "Stack")
kindsList.handleTapGesture = {(sender: UITapGestureRecognizer ) -> Void in
print("In UIViewController")
}
kindsList.frame = self.view.bounds // Update this to your requirement
view.addSubview(kindsList)