我将自定义视图设置为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 }
    }
}

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

将自定义视图设置为导航栏
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/

10-10 21:10