将搜索栏和搜索显示控制器添加到复杂的tableHeaderView时,UISearchBar在获得焦点时消失

时间:2015-01-18 17:59:03

标签: swift ios8 uisearchbar uisearchdisplaycontroller

我使用的是单个ViewController和一个关联的NIB,没有故事板。我准备把头发拉出来了。

问题

注意在聚焦后的视频中,在左上角可以看到一小部分字段,只有在点击UITableView上方的阴影区域后才能完全消失。进入视图层次结构时,它显示searchBar正在移出其原始的层级位置。

This video

NIB

Screenshot of the NIB, showing the structure of the tableHeaderView

守则

import UIKit 
class ViewController: UIViewController, UITableViewDataSource, 
UITableViewDelegate, UISearchDisplayDelegate, UISearchBarDelegate {

@IBOutlet weak var bigLabel: UILabel!
@IBOutlet weak var buttonGroupSegment: UISegmentedControl!
@IBOutlet var tableViewHeader: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet var searchBar: UISearchBar!

// MARK: VIEW CONTROLLER
override init() {
    super.init(nibName: "ViewController", bundle: nil)
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.initTableView();
}

override func viewDidLoad() {
    super.viewDidLoad();
    self.initLabelStyling();
    // Do any additional setup after loading the view, typically from a nib.
}

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

// MARK: TABLE VIEW HEADER
func initTableViewHeader() -> Void{
    self.tableView.tableHeaderView = self.tableViewHeader;

    self.initSearchView();
    self.initSegmentedControl();
}

// MARK: THE SEGMENTED CONTROL
func initSegmentedControl() -> Void{
    let font = UIFont(name: "HelveticaNeue", size: 10);
    let color = UIColor.whiteColor();
    let lighterColor = color.colorWithAlphaComponent(0.5);
    self.buttonGroupSegment.tintColor = UIColor.clearColor();
self.buttonGroupSegment.setTitleTextAttributes([NSForegroundColorAttributeName : lighterColor, NSFontAttributeName: font!, NSKernAttributeName: 0.7], forState: UIControlState.Normal)

    self.buttonGroupSegment.setTitleTextAttributes([NSForegroundColorAttributeName : color, NSFontAttributeName: font!], forState: UIControlState.Selected);

    // Change the case of all the titles
    let c = self.buttonGroupSegment.subviews.count;
    for i in 0..<c{
        if let title = self.buttonGroupSegment.titleForSegmentAtIndex(i){
            self.buttonGroupSegment.setTitle(title.uppercaseString, forSegmentAtIndex: i);
        }
    }

}

// MARK: SEARCH VIEW
func initSearchView() -> Void{
    let searchBar = self.searchDisplayController!.searchBar;
    searchBar.backgroundColor = UIColor.clearColor();
    searchBar.backgroundImage = UIImage();
    searchBar.barTintColor = UIColor.clearColor();
    searchBar.tintColor = UIColor.whiteColor()

    let numViews = searchBar.subviews[0].subviews.count;
    var searchField: UITextField?

    for i in 0..<numViews{
        if searchBar.subviews[0].subviews[i].isKindOfClass(UITextField.self) {
            searchField = searchBar.subviews[0].subviews[i] as? UITextField;
        }
    }

    if searchField != nil{

        // Fonts and colors
        let font = UIFont(name: "HelveticaNeue", size: 12);
        let textColor = UIColor.whiteColor();
        searchField!.font = font;
        searchField!.textColor = textColor;
        if searchField!.respondsToSelector("setAttributedPlaceholder:"){
            if let placeholder = searchField!.placeholder{
                let placeHolderColor = UIColor(red: 100, green: 100, blue: 100, alpha: 0.5);
                let attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName : placeHolderColor, NSFontAttributeName: font!]);
                searchField!.attributedPlaceholder = attributedPlaceholder;
            }
        }
        searchField!.backgroundColor = UIColor(red: 100, green: 100, blue: 100, alpha: 0.2);
        var searchIcon: UIImageView? = searchField?.leftView as? UIImageView;
        searchIcon!.image = searchIcon!.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
        searchIcon?.tintColor = UIColor.whiteColor();

        var clearIcon: UIImageView? = searchField?.rightView as? UIImageView;
        if clearIcon != nil{
            clearIcon!.image = clearIcon!.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
            clearIcon!.tintColor = UIColor.whiteColor();
        }
    }

}

// MARK: THE SEARCH VIEW DELEGATE METHODS
func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController) {

}

func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool {
    self.filterContentForSearchText(searchString, scope:"");
    return true;
}

func filterContentForSearchText(searchText: NSString, scope: String) -> Void{
    self.dataFiltered = self.data.filter({(pet: String) -> Bool in
        let stringMatch = pet.rangeOfString(searchText)
        return stringMatch != nil;
    })
}

// MARK: TABLE VIEW
let data = ["Cat","Dog","Bird","Fish","Ferret","Rat","Hamster","Chicken","Goat","Pig","Donkey","Monkey", "Rabbit", "Fox", "Snake", "Frog", "Spider","Rooster","Aligator","Pocupine","Squirrel","Duck","Turtle","Lizard","Lama"];
var dataFiltered: [String] = [];
let cellClass: String = "Cell";

func initTableView() -> Void{
    self.initTableViewHeader();
    self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellClass);


// MARK: TABLE VIEW DELEGATES AND DATA SOURCE METHODS
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

    if tableView == self.searchDisplayController!.searchResultsTableView{
        return self.dataFiltered.count
    }else{
        return self.data.count;
    }
}

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

    var cell: UITableViewCell?

    cell = self.tableView.dequeueReusableCellWithIdentifier(cellClass) as? UITableViewCell;

    if (cell == nil){
        cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: self.cellClass)
    }

    if tableView == self.searchDisplayController!.searchResultsTableView{
        cell?.textLabel?.text = self.dataFiltered[indexPath.row]
    }else{
        cell?.textLabel?.text = self.data[indexPath.row];
    }

    return cell!;
}

// MARK: STYLE THE LABEL (ADD A LINE)
func initLabelStyling()->Void{
    let v = UIView(frame: CGRectMake(0, 0, self.bigLabel.frame.width, 1));
    v.backgroundColor = UIColor(red: 100, green: 100, blue: 100, alpha: 0.2);
    self.bigLabel.addSubview(v)
}
}

1 个答案:

答案 0 :(得分:0)

这已经解决了吗?我知道这与导航控制器中的导航栏被覆盖在搜索栏顶部有关。如果您在iPhone 6的模拟器中运行它,然后将其转为横向,您可以在导航栏下看到搜索栏。如果我有解决方案,我会报告回来!

编辑:我们去了,明白了!

我添加了下面的内容(setNavigationBarHidden),它可能是一个更好的地方,但因为我只是原型,现在可以做:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if self.searchDisplayController!.active {
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        return self.filteredPlayers.count
    } else {
        return self.selectedPlayers.count
    }
}

...

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if self.searchDisplayController!.active {
        self.selectedPlayers.append(self.filteredPlayers[indexPath.row])
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        self.searchDisplayController!.setActive(false, animated: true)
        self.tableView.reloadData()
    }
}