【问题标题】:how to add subview at specific point in the view如何在视图中的特定点添加子视图
【发布时间】:2020-03-18 18:17:37
【问题描述】:

我正在向 tableView.tableHeaderView 添加一个 imageView 和 UISearchController.searchBar。但没有找到正确的方式在图片之后显示 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

但结果是这样的。 期望的结果就是这样。

【问题讨论】:

    标签: ios swift tableview nstableheaderview


    【解决方案1】:

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

    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
    

    最简单的方法

    【讨论】:

      【解决方案2】:

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

       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
      

      【讨论】:

      • searchController.searchBar 是一个只能获取的属性,因此无法使用框架。还设置约束放在图像顶部,因此为图像添加了约束,但没有运气,因此添加了一个视图并将约束添加到底部,然后添加了搜索控制器搜索器。但这会导致另一个问题。 tableview 位于 tableHeaderView 下
      猜你喜欢
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 1970-01-01
      相关资源
      最近更新 更多