【问题标题】:How do I set up my navigation search bar in Swift to look like the Reddit App如何在 Swift 中设置导航搜索栏,使其看起来像 Reddit 应用程序
【发布时间】:2020-03-06 01:31:30
【问题描述】:

我刚开始学习如何在 Xcode 中使用 Swift 进行编码,我需要一些关于搜索栏的帮助。我想在中心的导航栏中添加一个搜索字段栏,在它旁边我想添加两个项目。到目前为止,我设法将 UISearch 添加到我的导航栏,但是一旦我尝试在它旁边添加项目,它会将我的图标推到搜索字段上方。

按下状态

正常状态

有谁知道以编程方式或在情节提要中添加它旁边的两个菜单项吗?以及如何让搜索栏居中,并且稍微细一点?

我现在的代码:

override func viewDidLoad() {
    super.viewDidLoad()

    let searchController = UISearchController(searchResultsController: nil)
    searchController.delegate = self as? UISearchControllerDelegate

    let searchBar = searchController.searchBar
    searchBar.tintColor = UIColor.white
    searchBar.barTintColor = UIColor.white

    if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
        textfield.textColor = UIColor.blue
        if let backgroundview = textfield.subviews.first {

            // Background color
            backgroundview.backgroundColor = UIColor.white

            // Rounded corner
            backgroundview.layer.cornerRadius = 10;
            backgroundview.clipsToBounds = true;
        }
    }

    if let navigationbar = self.navigationController?.navigationBar {
        navigationbar.barTintColor = UIColor.blue
    }

    navigationItem.searchController = searchController
    navigationItem.hidesSearchBarWhenScrolling = false
    }

Reddit 示例

【问题讨论】:

  • 你能分享一下屏幕截图吗?
  • @RJ168 刚刚在帖子底部添加了两张关于它现在的外观的截图,它们是 reddit 应用程序之一

标签: ios swift xcode uisearchbar


【解决方案1】:

好的,解决了!刚刚使用了下面的代码。现在我的下一个难题是更改文本字段的背景。

//SEARCH
    let searchController = UISearchController(searchResultsController: nil)
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.delegate = self as? UISearchBarDelegate


    let frame = CGRect(x: 0, y: 0, width: 300, height: 44)
    let titleView = UIView(frame: frame)
    searchController.searchBar.backgroundImage = UIImage()
    searchController.searchBar.frame = frame
    titleView.addSubview(searchController.searchBar)
    navigationItem.titleView = titleView

    }

【讨论】:

    猜你喜欢
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多