草庐IT

ios - 每次点击取消按钮时,搜索栏都会向下跳一行

coder 2023-07-17 原文

我已经实现了一个 UISearchBar 来搜索来自外部 API 的项目目录。搜索功能按预期工作,但问题是每次我按下搜索栏文本字段右侧的取消按钮时,整个搜索栏向下移动一行,看起来它插入了整个搜索栏表格 View 也向下。

因此,如果我在搜索栏文本字段中键入一个字母,然后按取消,搜索栏文本字段将向下移动 44px,这是行高,并且 TableView 本身也会被下推相同的量。如果我连续按输入内容,然后按取消,搜索栏将在 View 中越来越远地移动。任何建议都会很棒!这是我的代码:

import Foundation
import UIKit
import ItemLogger


private extension Selector {
    static let dismiss = #selector(SearchVC.dismissView)
}


extension SearchVC: UISearchResultsUpdating {
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        let searchBar = searchController.searchBar
        let scope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex]
        filterContentForSearchText(searchController.searchBar.text!, scope: scope)
    }
}
extension SearchVC: UISearchBarDelegate {
    func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
        filterContentForSearchText(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope])
    }
}

class SearchVC: UITableViewController {

    let searchController = UISearchController(searchResultsController: nil)
    var searchedItems = [ItemLog]()
    var searchedImages = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()

        let leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "Back_Button"), style: UIBarButtonItemStyle.Plain, target: self, action: .dismiss)
        self.navigationItem.leftBarButtonItem = leftBarButtonItem
    }


    override func viewWillAppear(animated: Bool) {
        configureSearchController()
    }


    override func prefersStatusBarHidden() -> Bool {
        return true
    }


    func configureSearchController() {

        guard !searchController.active else {
            return
        }

        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Type to Search"

        definesPresentationContext = true
        searchController.searchBar.scopeButtonTitles = ["All"]
        searchController.searchBar.delegate = self
        searchController.searchBar.sizeToFit()
        tableView.tableHeaderView = searchController.searchBar

        let view: UIView = self.searchController.searchBar.subviews[0] as UIView
        for subView: UIView in view.subviews {
            if let textView = subView as? UITextField {
                textView.tintColor = UIColor.orangeColor()
                textView.textColor = UIColor.blackColor()
                textView.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.05)
            }
        }
        searchController.searchBar.barTintColor = UIColor.whiteColor()

        let cancelButtonAttributes: NSDictionary = [NSForegroundColorAttributeName: UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.33)]
        UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes as? [String : AnyObject], forState: UIControlState.Normal)
    }



    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        tableView.reloadData()
    }


    override func tableView(tableView:UITableView, numberOfRowsInSection section: Int) -> Int {
        if searchController.active && searchController.searchBar.text != "" {
            return searchedItems.count
        }

        return 0

    }

    override func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = self.tableView.dequeueReusableCellWithIdentifier("items", forIndexPath: indexPath)

        let label = cell.viewWithTag(111) as! UILabel
        let nameLabel = cell.viewWithTag(222) as! UILabel
        let art = cell.viewWithTag(333) as! UIImageView

        if searchController.active && searchController.searchBar.text != "" && searchController.searchBar.text != NSCharacterSet.whitespaceCharacterSet(){

            label.text = searchedItems[indexPath.row].title
            nameLabel.text = searchedItems[indexPath.row].name
            art.image = searchedImages[indexPath.row]
        }
        return cell
    }



    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        print(searchedItems[indexPath.row])
        self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }


    func filterContentForSearchText(searchText: String, scope: String = "All") {


        if searchController.active && searchController.searchBar.text != "" && searchController.searchBar.text != NSCharacterSet.whitespaceCharacterSet() {
            let queries: [SearchQueryOptions] = [
                .QueryString(searchController.searchBar.text!)]
            ItemLog.search(queries, completion: { (result) in
                if let itms = result.response.result where itms.count > 0 {
                    self.searchedItems.removeAll()
                    self.searchedImages.removeAll()
                    for i in 0...itms.count - 1 {

                        self.searchedItems.append(itms[i])
                        self.searchedImages.append(itms[i].img)

                    }
                }
                self.tableView.reloadData()
            })
        }
    }


    func dismissView(){
        self.navigationController?.popToRootViewControllerAnimated(true)
    }

}

最佳答案

在 Swift 3 中测试的代码。

注:什么时候,我,试试你的代码。我遇到了同样的问题。不知何故,我设法绕过了...

class SearchVC: UITableViewController,UISearchBarDelegate,UISearchResultUpdating {

var resultSearchController = UISearchController()

override func viewDidLoad() {
    super.viewDidLoad()

     configureSearchController()
 }


override var prefersStatusBarHidden: Bool {

    return true
}


func configureSearchController() {

    self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.hidesNavigationBarDuringPresentation = false
        controller.searchBar.searchBarStyle = .default
        controller.searchBar.sizeToFit()
        controller.searchBar.setShowsCancelButton(false, animated: true)
        controller.searchBar.keyboardAppearance = .default

        self.tableView.tableHeaderView = controller.searchBar

        //controller.searchBar.tintColor = UIColor(patternImage: UIImage(named: "xxxx")!)
        // controller.searchBar.setBackgroundImage(UIImage(named: "xxxx"), forBarPosition: UIBarPosition.Top, barMetrics: UIBarMetrics.Default)
        //  controller.searchBar.backgroundImage = UIImage(named: "xxxx")
        // controller.searchBar.setImage(UIImage(named: "search-icon.png"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal)

        return controller
    })()


    for subView in self.resultSearchController.searchBar.subviews
    {
        for subsubView in subView.subviews
        {
            if let textField = subsubView as? UITextField
            {
                textField.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("Search Text", comment: ""), attributes: [NSForegroundColorAttributeName: UIColor.red])

                textField.adjustsFontSizeToFitWidth = true
                textField.allowsEditingTextAttributes = true


                textField.textColor = UIColor.red
                textField.layer.borderColor = UIColor.gray.cgColor
                textField.layer.cornerRadius = 5
                textField.layer.masksToBounds = true

                textField.layer.borderWidth = 0.215

            }
         }  
      }
   }
}

更新:

  func updateSearchResults(for searchController: UISearchController) {}

上面代码的输出……希望我的回答能解决你的问题……

关于ios - 每次点击取消按钮时,搜索栏都会向下跳一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39982355/

有关ios - 每次点击取消按钮时,搜索栏都会向下跳一行的更多相关文章

  1. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  2. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  3. ruby-on-rails - Nokogiri:使用 XPath 搜索 <div> - 2

    我使用Nokogiri(Rubygem)css搜索寻找某些在我的html里面。看起来Nokogiri的css搜索不喜欢正则表达式。我想切换到Nokogiri的xpath搜索,因为这似乎支持搜索字符串中的正则表达式。如何在xpath搜索中实现下面提到的(伪)css搜索?require'rubygems'require'nokogiri'value=Nokogiri::HTML.parse(ABBlaCD3"HTML_END#my_blockisgivenmy_bl="1"#my_eqcorrespondstothisregexmy_eq="\/[0-9]+\/"#FIXMEThefoll

  4. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  5. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  6. ruby - 如何搜索有用的 ruby - 2

    寻找有用的ruby的好网站是什么? 最佳答案 AgileWebDevelopment列出插件(虽然不是ruby​​gems,我不确定为什么),并允许人们对它们进行评级。RubyToolbox按类别列出gem并比较它们的受欢迎程度。Rubygems有一个搜索框。StackOverflow对最有用的rails插件和ruby​​gems有疑问。 关于ruby-如何搜索有用的ruby,我们在StackOverflow上找到一个类似的问题: https://stacko

  7. ruby - 如何搜索、递增和替换 Ruby 字符串中的整数子字符串? - 2

    我有很多这样的文档:foo_1foo_2foo_3bar_1foo_4...我想通过获取foo_[X]的所有实例并将它们中的每一个替换为foo_[X+1]来转换它们。在这个例子中:foo_2foo_3foo_4bar_1foo_5...我可以用gsub和一个block来做到这一点吗?如果不是,最干净的方法是什么?我真的在寻找一个优雅的解决方案,因为我总是可以暴力破解它,但我觉得有一些正则表达式技巧值得学习。 最佳答案 我(完全)不懂Ruby,但类似这样的东西应该可以工作:"foo_1foo_2".gsub(/(foo_)(\d+)/

  8. ruby-on-rails - Rails 单选按钮 - 模型中多列的一种选择 - 2

    我希望用户从一个模型的三个选项中选择一个。即我有一个模型视频,可以被评为正面/负面/未知目前我有三列bool值(pos/neg/unknown)。这是处理这种情况的最佳方式吗?为此,表单应该是什么样的?目前我有类似的东西但显然它允许多项选择,而我试图将它限制为只有一个..怎么办? 最佳答案 如果要使用字符串列,让我们说rating。然后在你的表单中:#...#...它只允许一个选择编辑完全相同但使用radio_button_tag: 关于ruby-on-rails-Rails单选按钮-模

  9. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  10. ruby - Ruby 中的必应搜索 API - 2

    我读了"BingSearchAPI-QuickStart"但我不知道如何在Ruby中发出这个http请求(Weary)如何在Ruby中翻译“Stream_context_create()”?这是什么意思?"BingSearchAPI-QuickStart"我想使用RubySDK,但我发现那些已被弃用前(Rbing)https://github.com/mikedemers/rbing您知道Bing搜索API的最新包装器(仅限Web的结果)吗? 最佳答案 好吧,经过一个小时的挫折,我想出了一个办法来做到这一点。这段代码很糟糕,因为它是

随机推荐