如何在自定义 TitleView 的子视图上添加子视图
Posted
技术标签:
【中文标题】如何在自定义 TitleView 的子视图上添加子视图【英文标题】:How to add subview on custom TitleView's subview 【发布时间】:2019-02-13 06:34:07 【问题描述】:我将自定义视图设置为 UINavigationBar 的 titleView。 当我只是用框架设置视图时,它工作正常。
但是,如果我将任何子视图添加到我设置为标题视图的视图中,它就不会出现。
添加到 titleView 的视图
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
视图控制器声明
private lazy var searchBar: UIView =
let sb = NavigationBarSearchBar(frame: CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 40))
return sb
()
将自定义视图设置为导航栏
navigationItem.titleView = searchBar
【问题讨论】:
您需要在 titleView 或 searchBar 中输入文字??顺便说一句,用于搜索栏 -> search-bar-in-navigation-bar-title 我能够成功地将搜索栏嵌入到 UINavigationBar 但是这样做对我有一些问题。仅当搜索栏具有焦点时,取消按钮才设置为禁用。我需要一直启用取消按钮。如果我可以轻松复制它,我会更好地处理所有可能的事件,这可能会使取消按钮被禁用(并且很多)。 您能否更新您的问题并提及您面临的问题。 【参考方案1】:lazy var searchBar:UISearchBar = UISearchBar(frame: CGRectMake(0, 0, 200, 20))
searchBar.sizeToFit()
navigationItem.titleView = searchBar
【讨论】:
【参考方案2】:使用 Frame 创建视图并添加到 navigationItem
var viewTitle = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
viewTitle.backgroundColor = UIColor.red
navigationItem?.titleView = viewTitle
【讨论】:
以上是关于如何在自定义 TitleView 的子视图上添加子视图的主要内容,如果未能解决你的问题,请参考以下文章
如何在自定义滑动(而不是滑动删除)单元格(滑动到邮件/短信)中点击一个单元格时删除在其他 TableView 单元格中添加的子视图