0
votes

I have a code to show an activity indicator in Swift, but it's not working properly.

The activity indicator doesn't appear, even after all the code inside the configuration func is loaded correctly.

What is going wrong in the code?

Here is the code and the image:

import UIKit

class SelecionaPaisViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {

    //MARK: - Outlets
    @IBOutlet weak var paisesTableView: UITableView!

    //MARK: - Propriedades
    var paises = [PaisCodigo]()
    var paisesFiltrado = [PaisCodigo]()

    var controladorDeBusca: UISearchController!

    var container: UIView = UIView()
    var loadingView: UIView = UIView()
    var indicadorDeAtividade: UIActivityIndicatorView!

    //MARK: - Métodos reescritos da View
    override func viewDidLoad() {
        super.viewDidLoad()

        paisesTableView.delegate = self
        paisesTableView.dataSource = self

        //Carrega configuração do SearchController
        configurarControladorDeBusca()

        //Carrega indicador de atividade
        configurarIndicadorDeAtividade()

        //Dados dos países
        carregaDadosPaises()

        //Configura comportamento da tabela
        configuraComportamentoDaTabela()
    }

    override func viewDidAppear(animated: Bool) {
        //Inicia
        iniciaIndicadorDeAtividade()
    }

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

    // MARK: - Métodos da Table view data source
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if controladorDeBusca.active {
            return paisesFiltrado.count
        } else {
            return paises.count
        }
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("PaisCell", forIndexPath: indexPath)

        let pais: PaisCodigo

        if controladorDeBusca.active {
            pais = paisesFiltrado[indexPath.row]
        } else {
            pais = paises[indexPath.row]
        }

        cell.textLabel?.text = pais.nome + " (+" + String(pais.codigo) + ")"

        if pais.nome != pais.nomeIngles {
            cell.detailTextLabel?.text = pais.nomeIngles
        } else {
            cell.detailTextLabel?.text = ""
        }

        return cell
    }

    //MARK: - Métodos do UISearchResultsUpdating
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        //paisesFiltrado.removeAll(keepCapacity: false)

        filtrarBusca(controladorDeBusca.searchBar.text!)
    }

    //MARK: - Métodos
    func carregaDadosPaises() {
        //Carrega dados dos países
        let pais1 = PaisCodigo(nome: "Brasil", nomeIngles: "Brazil", codigo: 55)
        let pais2 = PaisCodigo(nome: "United States", nomeIngles: "United States", codigo: 1)
        let pais3 = PaisCodigo(nome: "Argentina", nomeIngles: "Argentina", codigo: 54)
        let pais4 = PaisCodigo(nome: "Australia", nomeIngles: "Australia", codigo: 61)

        paises += [pais1, pais2, pais3, pais4]

        //paisesTableView.reloadData()
    }

    func configurarControladorDeBusca() {
        //Configura Controlador de Busca
        controladorDeBusca = UISearchController(searchResultsController: nil)
        controladorDeBusca.searchResultsUpdater = self
        controladorDeBusca.dimsBackgroundDuringPresentation = false
        definesPresentationContext = true

        controladorDeBusca.loadViewIfNeeded()

        //Configura a barra do Controlador de busca
        controladorDeBusca.searchBar.placeholder = "Search country"
        controladorDeBusca.searchBar.sizeToFit()
        controladorDeBusca.searchBar.barTintColor = navigationController?.navigationBar.barTintColor
        //controladorDeBusca.searchBar.translucent = true
        controladorDeBusca.searchBar.tintColor = UIColor.whiteColor()

        //Adiciona a barra do Controlador de Busca a Table View
        paisesTableView.tableHeaderView = controladorDeBusca.searchBar
    }

    func configurarIndicadorDeAtividade() {

        container.frame = paisesTableView.frame
        container.center = paisesTableView.center
        container.backgroundColor = UIColorFromHex(0xffffff, alpha: 0.2)

        loadingView.frame = CGRectMake(0, 0, 80, 80)
        loadingView.center = container.center
        loadingView.backgroundColor = UIColorFromHex(0x444444, alpha: 0.4)
        loadingView.clipsToBounds = true
        loadingView.layer.cornerRadius = 10

        //Configura Indicador de atividade
        indicadorDeAtividade = UIActivityIndicatorView()
        indicadorDeAtividade.center = loadingView.center
        indicadorDeAtividade.hidesWhenStopped = true
        indicadorDeAtividade.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
        indicadorDeAtividade.tintColor = UIColor.redColor()

        //Adiciona o indicador a View
        container.addSubview(loadingView)
        loadingView.addSubview(indicadorDeAtividade)
        view.addSubview(container)

        indicadorDeAtividade.hidden = false
    }

    func iniciaIndicadorDeAtividade() {
        indicadorDeAtividade.startAnimating()
    }

    func paraIndicadorDeAtividade() {

    }

    func configuraComportamentoDaTabela() {
        paisesTableView.hidden = !indicadorDeAtividade.hidden
        paisesTableView.userInteractionEnabled = !paisesTableView.hidden
    }

    func filtrarBusca(textoDeBusca: String) {
        //Filtrar resultados de busca
        paisesFiltrado = paises.filter{ PaisCodigo in
            return PaisCodigo.nome.lowercaseString.containsString(textoDeBusca.lowercaseString) || PaisCodigo.nomeIngles.lowercaseString.containsString(textoDeBusca.lowercaseString)
        }

        paisesTableView.reloadData()
    }

    func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor {
        //Conversor de cores em HEX
        let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
        let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
        let blue = CGFloat(rgbValue & 0xFF)/256.0
        return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
    }

enter image description here

1
I looks like you are tying to create a view and spinning activity indicator on top of it. Did you try removing the grey view that shows up in your picture and see if the activity indicator is behind it? Also, to speed up development, I would highly recommend MBProgressHUD: github.com/jdg/MBProgressHUD and here is video that shows how to convert the Objective C code into swift: youtube.com/watch?v=vwkOERJvuL0Dan Levy
I think what is happening is this, but how can I bring the Activity indicator over the loading view? I tried loadingView.insertSubview(indicadorDeAtividade, aboveSubview: loadingView) but it didn't work.GuiDupas

1 Answers

1
votes

Your indicadorDeAtividade.center is incorrect. The center property of a UIView uses the coordinate system of the superview, so you've placed your activity indicator way off screen.

In the function configurarIndicadorDeAtividade, replace:

indicadorDeAtividade.center = loadingView.center

with:

indicadorDeAtividade.center = CGPointMake(loadingView.frame.width / 2, loadingView.frame.height / 2)