【发布时间】:2021-09-29 07:37:24
【问题描述】:
我创建了一个 UICollectionViewController 来模拟一个 Feed 应用程序,我想配置类似于 Twitter 的顶部导航栏,带有触发操作的自定义按钮,这是我的
我面临的问题是,当我点击黑色个人资料图标时,没有触发该操作。
这是我的代码:
import UIKit
class HomeViewController: UICollectionViewController {
//MARK: - Properties
private lazy var profileButton: UIButton = {
let button = UIButton(type: .system)
button.setImage(UIImage(systemName: "person.fill"), for: .normal)
button.tintColor = UIColor(rgb: 0x79CBBF)
button.addTarget(self, action: #selector(didTapProfile), for: .touchUpInside)
return button
}()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupNavBar()
}
// MARK: - Helpers
func setupNavBar() {
let width = view.frame.width
let titleView = UIView()
titleView.backgroundColor = .clear
titleView.frame = .init(x: 0, y: 0, width: width, height: 50)
titleView.addSubview(profileButton)
profileButton.tintColor = .black
profileButton.centerY(inView: titleView, leftAnchor: titleView.leftAnchor, paddingLeft: 0)
titleView.addSubview(filterButton)
filterButton.centerY(inView: titleView, leftAnchor: profileButton.rightAnchor, paddingLeft: view.frame.width - 60 - 16)
navigationItem.titleView = titleView
}
// MARK: - Actions
@objc func didTapProfile() {
print("did tap profile")
}
如下所述,我向按钮添加了一个 .addTarget,但当按钮位于导航栏内时,#selector(didTapProfile) 函数不会被触发。
关于如何做到这一点的任何提示?
【问题讨论】:
-
我觉得你在使用
titleView之类的东西时做错了。 UINavigationBar 提供了各种便利。
标签: swift xcode navigationbar