简体   繁体   中英

Swift UISearchController when select item search bar is still there

I have two problems with UISearchController . I use this setup for UISearchController:

var resultSearchController = UISearchController(searchResultsController: nil)

override func viewDidLoad() {
    super.viewDidLoad()

    resultSearchController = UISearchController(searchResultsController: nil)
    resultSearchController.searchResultsUpdater = self
    resultSearchController.dimsBackgroundDuringPresentation = false
    resultSearchController.hidesNavigationBarDuringPresentation = false
    resultSearchController.searchBar.placeholder = "Traži.."
    resultSearchController.searchBar.sizeToFit()
    tableView.tableHeaderView = resultSearchController.searchBar

    refreshControl = UIRefreshControl()
    refreshControl!.attributedTitle = NSAttributedString(string: "Učitaj podatke..")
    refreshControl!.backgroundColor = UIColor(red:1, green:0.48, blue:0, alpha:0.3)
    refreshControl!.tintColor = UIColor.whiteColor()
    refreshControl!.addTarget(self, action: #selector(ArticleTableViewController.getArticleData), forControlEvents: UIControlEvents.ValueChanged)
    tableView.addSubview(refreshControl!)
}

First problem

when i click on search bar textfield, UIRefreshControl shows but it shouldn't:

在此处输入图片说明

Second problem

when i search for item, and click on it, i use Storyboard segue to open that item in new viewcontroller, but problem is that search bar is still there on that new VC(first image is searching, second image shows new VC opened):

在此处输入图片说明 在此处输入图片说明

I found this solution:

override func viewDidLoad() {
    super.viewDidLoad()

    resultSearchController = UISearchController(searchResultsController: nil)
    resultSearchController.searchResultsUpdater = self
    resultSearchController.dimsBackgroundDuringPresentation = false
    resultSearchController.hidesNavigationBarDuringPresentation = false
    resultSearchController.searchBar.placeholder = "Traži.."
    resultSearchController.searchBar.sizeToFit()
    tableView.tableHeaderView = resultSearchController.searchBar

    refreshControl = UIRefreshControl()
    refreshControl!.attributedTitle = NSAttributedString(string: "Učitaj podatke..")
    refreshControl!.backgroundColor = UIColor(red:1, green:0.48, blue:0, alpha:0.3)
    refreshControl!.tintColor = UIColor.whiteColor()
    refreshControl!.addTarget(self, action: #selector(ArticleTableViewController.getArticleData), forControlEvents: UIControlEvents.ValueChanged)
    tableView.addSubview(refreshControl!)


    // this hide search bar on next VC, first problem 
    self.definesPresentationContext = true
    // second problem
    tableView.contentOffset = CGPointMake(0, CGRectGetHeight(resultSearchController.searchBar.frame));

}

May be you should use a UISearchBar instead of the UISearchController? Try this code:

ViewController.swift

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {

@IBOutlet var searchBar: UISearchBar!
@IBOutlet var tableView: UITableView!


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    tableView.dataSource = self
    tableView.delegate = self
    searchBar.delegate = self
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 40
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell")
    cell?.textLabel?.text = "\(indexPath.row)"
    return cell!
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let newViewController = UIViewController()
    newViewController.view.backgroundColor = UIColor.whiteColor()
    newViewController.title = "\(indexPath.row)"
    navigationController?.pushViewController(newViewController, animated: true)
}


func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    NSLog(searchText)
}
}

Main.storyboard

在此处输入图片说明

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15G31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="u8Q-4a-0UD">
<dependencies>
    <deployment identifier="iOS"/>
    <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
</dependencies>
<scenes>
    <!--View Controller-->
    <scene sceneID="tne-QT-ifu">
        <objects>
            <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_38971807" customModuleProvider="target" sceneMemberID="viewController">
                <layoutGuides>
                    <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                    <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                </layoutGuides>
                <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                    <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
                    <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                    <subviews>
                        <searchBar contentMode="redraw" translatesAutoresizingMaskIntoConstraints="NO" id="GdH-fg-5TJ">
                            <rect key="frame" x="0.0" y="64" width="600" height="44"/>
                            <textInputTraits key="textInputTraits"/>
                        </searchBar>
                        <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="tP2-Xq-aem">
                            <rect key="frame" x="0.0" y="108" width="600" height="492"/>
                            <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                            <prototypes>
                                <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="cell" textLabel="RcZ-LI-9Ir" style="IBUITableViewCellStyleDefault" id="13y-5Y-dcw">
                                    <rect key="frame" x="0.0" y="28" width="600" height="44"/>
                                    <autoresizingMask key="autoresizingMask"/>
                                    <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="13y-5Y-dcw" id="ldM-4e-kie">
                                        <rect key="frame" x="0.0" y="0.0" width="600" height="43"/>
                                        <autoresizingMask key="autoresizingMask"/>
                                        <subviews>
                                            <label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="RcZ-LI-9Ir">
                                                <rect key="frame" x="15" y="0.0" width="570" height="43"/>
                                                <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="16"/>
                                                <color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
                                                <nil key="highlightedColor"/>
                                            </label>
                                        </subviews>
                                    </tableViewCellContentView>
                                </tableViewCell>
                            </prototypes>
                        </tableView>
                    </subviews>
                    <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
                    <constraints>
                        <constraint firstItem="GdH-fg-5TJ" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="Fwk-Jx-EJc"/>
                        <constraint firstAttribute="trailing" secondItem="GdH-fg-5TJ" secondAttribute="trailing" id="Q3j-AV-Tnj"/>
                        <constraint firstItem="tP2-Xq-aem" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="T9u-C9-1HD"/>
                        <constraint firstItem="GdH-fg-5TJ" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" id="Y9o-yO-w6R"/>
                        <constraint firstItem="GdH-fg-5TJ" firstAttribute="leading" secondItem="tP2-Xq-aem" secondAttribute="leading" id="l4X-RD-XEW"/>
                        <constraint firstItem="GdH-fg-5TJ" firstAttribute="trailing" secondItem="tP2-Xq-aem" secondAttribute="trailing" id="pcF-ST-Zkq"/>
                        <constraint firstItem="tP2-Xq-aem" firstAttribute="top" secondItem="GdH-fg-5TJ" secondAttribute="bottom" id="ze4-D7-NeF"/>
                    </constraints>
                </view>
                <navigationItem key="navigationItem" id="pJE-Q4-d47"/>
                <connections>
                    <outlet property="searchBar" destination="GdH-fg-5TJ" id="N81-72-8HH"/>
                    <outlet property="tableView" destination="tP2-Xq-aem" id="lYV-er-UNj"/>
                </connections>
            </viewController>
            <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
        </objects>
        <point key="canvasLocation" x="1075" y="-133"/>
    </scene>
    <!--Navigation Controller-->
    <scene sceneID="Q5J-kb-qjE">
        <objects>
            <navigationController automaticallyAdjustsScrollViewInsets="NO" id="u8Q-4a-0UD" sceneMemberID="viewController">
                <toolbarItems/>
                <navigationBar key="navigationBar" contentMode="scaleToFill" id="ey2-Nm-1yZ">
                    <rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
                    <autoresizingMask key="autoresizingMask"/>
                </navigationBar>
                <nil name="viewControllers"/>
                <connections>
                    <segue destination="BYZ-38-t0r" kind="relationship" relationship="rootViewController" id="A3N-1a-Rlv"/>
                </connections>
            </navigationController>
            <placeholder placeholderIdentifier="IBFirstResponder" id="QFX-N3-4dT" userLabel="First Responder" sceneMemberID="firstResponder"/>
        </objects>
        <point key="canvasLocation" x="218" y="-133"/>
    </scene>
</scenes>
</document>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM