gpt4 book ai didi

ios - 如何在自定义 TitleView 的 subview 上添加 subview

转载 作者:搜寻专家 更新时间:2023-11-01 06:54:19 26 4
gpt4 key购买 nike

我将自定义 View 设置为 UINavigationBar 的 titleView。当我只设置带框架的 View 时,它工作正常。

但是,如果我将任何 subview 添加到我设置为标题 View 的 View 中,它就不会出现。


添加到 titleView 的 View

class NavigationBarSearchBar: UIView {

let view: UIView = {
let v = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()


override init(frame: CGRect) {
super.init(frame: frame)
setupSubviews()
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}


private func setupSubviews() {

addSubview( view )
[
view.widthAnchor.constraint(equalToConstant: 20),
view.heightAnchor.constraint(equalToConstant: 20),
view.centerYAnchor.constraint(equalTo: centerYAnchor),
view.centerXAnchor.constraint(equalTo: centerXAnchor)
].forEach { $0.isActive = true }
}
}


View Controller 声明

private lazy var searchBar: UIView = {
let sb = NavigationBarSearchBar(frame: CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 40))
return sb
}()


将自定义 View 设置为导航栏

navigationItem.titleView = searchBar

最佳答案

lazy   var searchBar:UISearchBar = UISearchBar(frame: CGRectMake(0, 0, 200, 20))
searchBar.sizeToFit()
navigationItem.titleView = searchBar

关于ios - 如何在自定义 TitleView 的 subview 上添加 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54663983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com