Search code examples
iosswiftsearchuisegmentedcontrol

Reloading TableView using UISegmentedControl in Swift


I am creating a search screen where you can select among four different options. If one selects people, then people array gets loaded in table view cells , if he selects images then image posts get loaded in tableview .

screenshot of the app

how can i achieve the design posted above? i have created four different cells and nib files and based on the option selected in segment control , i have to load those nib files in table cell.

UPDATE ::::

I am updating all my code here which i have combined into one file.

import UIKit
import Alamofire

class SearchViewController: UIViewController , UITableViewDataSource , UITableViewDelegate , UISearchBarDelegate{


var imagepost : ImageSeachPostData!
var imageposts = [ImageSeachPostData]()
var videopost : VideoSeachPostData!
var videoposts = [VideoSeachPostData]()
var statuspost : StatusSearchPostData!
var statusposts = [StatusSearchPostData]()
var penpalpost : PenpalSearchPostData!
var penpalposts = [PenpalSearchPostData]()
var tablearray : NSArray = []



typealias DownloadComplete = () -> ()

@IBOutlet weak var searchTable: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var searchTypeSegmentControl: UISegmentedControl!
override func viewDidLoad() {
    super.viewDidLoad()
    searchTable.dataSource = self
    searchTable.delegate = self
    searchBar.delegate = self
    searchPassed()

}
    @IBAction func onChangeSegment(_ sender: UISegmentedControl)
    {
        self.searchTable.reloadData()
    }


    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        view.endEditing(true)
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        if searchBar.text == nil || searchBar.text == "" {

            searchTable.reloadData()
            view.endEditing(true)

        } else {

            searchPassed()
            searchTable.reloadData()

        }

    }

func searchPassed()
{
    let searchText = "Postpositives" 
    print(searchText)
    var request = URLRequest(url: URL(string: "https://www.example.com/search")!)
    request.httpMethod = "GET"
    let postString = "q=\(searchText)"
    request.httpBody = postString.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(String(describing: error))")
            print("cant run")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
            print("\(searchText)")


        }
        else {
            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(String(describing: responseString))")
   //             func downloadPostData(completed: @escaping DownloadComplete) {
                Alamofire.request("https://www.example.com/api/search?q=\(searchText)").responseJSON { response in
                    let result = response.result
                    if let dict = result.value as? Dictionary<String,AnyObject> {

                        if let successcode = dict["STATUS_CODE"] as? Int {
                            if successcode == 1 {
                                if let postsArray = dict["posts"] as? [Dictionary<String,AnyObject>]
                                {
                                    for obj in postsArray
                                    {
                                        let mediatype = dict["media_type"] as! String?
                                        if mediatype == "image"
                                        {
                                        let imagepost = ImageSeachPostData(postDict: obj)
                                        self.imageposts.append(imagepost)
                                        }
                                        else if mediatype == "video"
                                        {
                                        let videopost = VideoSeachPostData(postDict: obj)
                                        self.videoposts.append(videopost)
                                        }
                                        else if mediatype == "null"
                                        {
                                        let statuspost = StatusSearchPostData(postDict: obj)
                                        self.statusposts.append(statuspost)
                                        }
                                        let penpalpost = PenpalSearchPostData(postDict: obj)
                                        self.penpalposts.append(penpalpost)

                                    }
                                    self.searchTable.reloadData()
                                }
                            }
                        }
                    }
                }
            }



        }
       }
            task.resume()


}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    let selectedIndex = self.searchTypeSegmentControl.selectedSegmentIndex
    switch selectedIndex
    {
    case 0:
        return penpalposts.count
    case 1:
        return statusposts.count
    case 2:
        return imageposts.count
    case 3:
        return videoposts.count

    default:
        return 0
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let selectedIndex = self.searchTypeSegmentControl.selectedSegmentIndex
    switch selectedIndex
    {
    case 0:
        return tableView.dequeueReusableCell(withIdentifier: "penpalSearchReuse", for: indexPath)
    case 1:
        return tableView.dequeueReusableCell(withIdentifier: "statusSearchReuse", for: indexPath)

    case 2:
        return tableView.dequeueReusableCell(withIdentifier: "imageSearchReuse", for: indexPath)
    case 3:
        return tableView.dequeueReusableCell(withIdentifier: "videoSearchReuse", for: indexPath)

    default:
        return UITableViewCell()
}
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return 420
}


}

Solution

  • Use selectedSegmentIndex property of UISegmentedControl to handle the UITableViewDataSource according to the selected segment.

    Example:

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        let selectedIndex = self.segmentedControl.selectedSegmentIndex
        switch selectedIndex
        {
        case 0:
            return peopleArray.count
        case 1:
            return imagesArray.count
        //Add other cases here
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let selectedIndex = self.segmentedControl.selectedSegmentIndex
        switch selectedIndex
        {
        case 0:
            return tableView.dequeueReusableCell(withIdentifier: "peopleCell", for: indexPath) //Do your custom handling whatever required.
        case 1:
            return tableView.dequeueReusableCell(withIdentifier: "imageCell", for: indexPath)
        //Add other cases here
        default:
            return UITableViewCell()
        }
    }
    
    @IBAction func onChangeSegment(_ sender: UISegmentedControl)
    {
        self.tableView.reloadData()
    }