热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

IhaveimplementedaUISearchBartosearchthroughacatalogueofitemsfromanexternalAPI.TheSe

I have implemented a UISearchBar to search through a catalogue of items from an external API. The Search functionality works as expected, however the problem is that every time I press the cancel button, which is on the right side of the search bar text field, the whole search bar moves down by one row and it looks like it pushes the entire table view down as well.

我已经实现了一个UISearchBar来搜索外部API中的项目目录。搜索功能按预期工作,但问题是每次按下取消按钮(位于搜索栏文本字段的右侧)时,整个搜索栏向下移动一行,看起来它会推动整个表视图也是如此。

So if I type a letter into the search bar text field, then press cancel, the search bar text field moves down by 44px, which is the row height, and the table view itself also gets pushed down by the same amount. If i continuously press type something, then press cancel, the search bar will move further and further down the view. Any advice would be great! Here is my code:

因此,如果我在搜索栏文本字段中键入一个字母,然后按取消,搜索栏文本字段向下移动44px,这是行高,并且表视图本身也会被按下相同的量。如果我连续按类型,然后按取消,搜索栏将在视图中进一步向下移动。任何建议都会很棒!这是我的代码:

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)
    }

}

3 个解决方案

#1


7  

Code tested in Swift 3.

代码在Swift 3中测试过。

Note: When, I, try your code. I was facing the same issue. Somehow, I managed to get around...

注意:我何时尝试使用您的代码。我面临同样的问题。不知何故,我设法绕过...

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

            }
         }  
      }
   }
}

Updated:

更新:

  func updateSearchResults(for searchController: UISearchController) {}

Output from above code..hope, my answer will fix your problem.... enter image description here

从上面的代码输出..希望,我的答案将解决你的问题....

#2


0  

Try to call configureSearchController() in viewDidLoad. And don't forget to call super.viewWillAppear(animated:) in your viewWillAppear.

尝试在viewDidLoad中调用configureSearchController()。并且不要忘记在viewWillAppear中调用super.viewWillAppear(animated :)。

#3


0  

I've made an open source project SearchTableView

我做了一个开源项目SearchTableView

self.searchController.searchBar.sizeToFit()
self.tableHeaderView = self.searchController.searchBar

searchTableView.layoutMargins = UIEdgeInsets.zero
definesPresentatiOnContext= true
extendedLayoutIncludesOpaqueBars = true

推荐阅读
  • 安卓select模态框样式改变_微软Office风格的多端(Web、安卓、iOS)组件库——Fabric UI...
    介绍FabricUI是微软开源的一套Office风格的多端组件库,共有三套针对性的组件,分别适用于web、android以及iOS,Fab ... [详细]
  • IhaveconfiguredanactionforaremotenotificationwhenitarrivestomyiOsapp.Iwanttwodiff ... [详细]
  • Python爬虫中使用正则表达式的方法和注意事项
    本文介绍了在Python爬虫中使用正则表达式的方法和注意事项。首先解释了爬虫的四个主要步骤,并强调了正则表达式在数据处理中的重要性。然后详细介绍了正则表达式的概念和用法,包括检索、替换和过滤文本的功能。同时提到了re模块是Python内置的用于处理正则表达式的模块,并给出了使用正则表达式时需要注意的特殊字符转义和原始字符串的用法。通过本文的学习,读者可以掌握在Python爬虫中使用正则表达式的技巧和方法。 ... [详细]
  • 本文介绍了如何使用PHP向系统日历中添加事件的方法,通过使用PHP技术可以实现自动添加事件的功能,从而实现全局通知系统和迅速记录工具的自动化。同时还提到了系统exchange自带的日历具有同步感的特点,以及使用web技术实现自动添加事件的优势。 ... [详细]
  • vue使用
    关键词: ... [详细]
  • 本文讨论了如何在不使用SearchBar display controller的情况下,单独使用SearchBar并捕获其textChange事件。作者介绍了实际状况,即左侧SliderMenu中的SearchBar需要在主页TableView中显示搜索结果。然后,作者提供了解决方案和步骤,帮助读者实现这一功能。 ... [详细]
  • javascript  – 概述在Firefox上无法正常工作
    我试图提出一些自定义大纲,以达到一些Web可访问性建议.但我不能用Firefox制作.这就是它在Chrome上的外观:而那个图标实际上是一个锚点.在Firefox上,它只概述了整个 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 本文介绍了iOS数据库Sqlite的SQL语句分类和常见约束关键字。SQL语句分为DDL、DML和DQL三种类型,其中DDL语句用于定义、删除和修改数据表,关键字包括create、drop和alter。常见约束关键字包括if not exists、if exists、primary key、autoincrement、not null和default。此外,还介绍了常见的数据库数据类型,包括integer、text和real。 ... [详细]
  • iOS Swift中如何实现自动登录?
    本文介绍了在iOS Swift中如何实现自动登录的方法,包括使用故事板、SWRevealViewController等技术,以及解决用户注销后重新登录自动跳转到主页的问题。 ... [详细]
  • 程序员如何选择机械键盘轴体?红轴和茶轴对比
    本文介绍了程序员如何选择机械键盘轴体,特别是红轴和茶轴的对比。同时还介绍了U盘安装Linux镜像的步骤,以及在Linux系统中安装软件的命令行操作。此外,还介绍了nodejs和npm的安装方法,以及在VSCode中安装和配置常用插件的方法。最后,还介绍了如何在GitHub上配置SSH密钥和git的基本配置。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 本文详细介绍了Spring的JdbcTemplate的使用方法,包括执行存储过程、存储函数的call()方法,执行任何SQL语句的execute()方法,单个更新和批量更新的update()和batchUpdate()方法,以及单查和列表查询的query()和queryForXXX()方法。提供了经过测试的API供使用。 ... [详细]
  • 开发笔记:Docker 上安装启动 MySQL
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Docker上安装启动MySQL相关的知识,希望对你有一定的参考价值。 ... [详细]
  • 恶意软件分析的最佳编程语言及其应用
    本文介绍了学习恶意软件分析和逆向工程领域时最适合的编程语言,并重点讨论了Python的优点。Python是一种解释型、多用途的语言,具有可读性高、可快速开发、易于学习的特点。作者分享了在本地恶意软件分析中使用Python的经验,包括快速复制恶意软件组件以更好地理解其工作。此外,作者还提到了Python的跨平台优势,使得在不同操作系统上运行代码变得更加方便。 ... [详细]
author-avatar
陈可1993_532
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有