gpt4 book ai didi

swift - NavigationItem TitleView 约束不起作用

转载 作者:行者123 更新时间:2023-11-30 11:07:07 34 4
gpt4 key购买 nike

我想使用 UITextField 创建一个搜索栏。我尝试将 NavigationItem 的 TitleView 设置为文本字段并设置相应的约束。但导航栏中央的文本字段仍然很短。如何让文本框填满整个导航栏?这是我的代码:

cancelbtn = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(CourseTableViewController.searchCancelled))
self.navigationItem.leftBarButtonItem = cancelbtn

let searchField = UITextField()
searchField.translatesAutoresizingMaskIntoConstraints = false
searchField.borderStyle = .roundedRect
self.navigationItem.titleView = searchField
self.navigationItem.titleView!.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: cancelbtn.width)
self.navigationItem.titleView!.widthAnchor.constraint(equalToConstant: view.frame.size.width - cancelbtn.width)

它看起来是这样的: UIView

最佳答案

您应该阅读 Apple 的相关指南。从 iOS11 开始,您应该将 searchBar 安装到 navigationItem 中。尝试使用此代码:

import UIKit

class ViewController: UIViewController, UISearchControllerDelegate {

var searchController = UISearchController()

override func viewDidLoad() {
super.viewDidLoad()

navigationController?.navigationBar.prefersLargeTitles = false
searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self

// Customisation
searchController.searchBar.tintColor = .black
searchController.dimsBackgroundDuringPresentation = false

navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
}

}

关于swift - NavigationItem TitleView 约束不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52583871/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com