繁体   English   中英

如何在视图中的特定点添加子视图

[英]how to add subview at specific point in the view

我将 imageView 和 UISearchController.searchBar 添加到 tableView.tableHeaderView。 但没有找到正确的方法在图像之后显示 searchBar。

    let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 333))
    let image = UIImageView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 269))
    image.image = #imageLiteral(resourceName: "map")
    view.addSubview(image)
    view.insertSubview(searchController.searchBar, at: 1)//insertSubview(searchController.searchBar, belowSubview: image)
    self.tableView.tableHeaderView = view

但结果是这样的。 在此处输入图像描述 期望的结果就是这样。 在此处输入图像描述

如果您想在视图底部添加搜索栏 您可以以编程方式添加搜索栏并将其固定到视图底部

view.addSubview(searchBar)

searchBar.bottomAnchor.constraint(equalTo: view.trailingAnchor).isActive =true
searchBar.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
searchBar.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
searchBar.heightAnchor.constraint(equalToConstant: 50).isActive = true

最简单的方法

如果您不想使用自动布局,请尝试提供搜索栏框架

 searchBar?.frame = CGRect(x: 0, y: view.frame.size.height-searchBar!.frame.size.height  , width: UIScreen.main.bounds.width, height: searchBar?.frame.size.height ?? 44)


If you are using auto-layout add bottom constraint to searchbar.
    view.addSubview(searchBar!)
searchBar!.translatesAutoresizingMaskIntoConstraints = false
searchBar!.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
searchBar!.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
searchBar!.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
searchBar!.heightAnchor.constraint(equalToConstant: 44).isActive = true

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM