uitableview,swift,uisearchbar,uisearchdisplaycontroller,xcode6.3 , Implement Search bar and search display for the table view with sections


Implement Search bar and search display for the table view with sections

Question:

Tag: uitableview,swift,uisearchbar,uisearchdisplaycontroller,xcode6.3

I am trying to implement search bar with search display feature in swift for the table view given below.

Screenshot of the table view

enter image description here

I am getting issue because my string array is in the following format.

["section name1" : ["list1", "list2"] ,"section name2" : ["list3", "list4"]]

I have added my code below for the table view.

    @IBOutlet weak var dishtable: UITableView!

@IBOutlet weak var namlbl: UILabel!
var Dishes = ["POPULAR Dishes": ["Biryani", "Tandori Chicken","Butter Chicken", "Vada Pav"],"A": ["Aloo baingan", "Aloo ki Tikki", "Amritsari fish"], "B": ["Baigan bharta", "Biryani"]];

var Filterval = ["POPULAR Dishes": ["Biryani", "Tandori Chicken","Butter Chicken", "Vada Pav"],"A": ["Aloo baingan", "Aloo ki Tikki", "Amritsari fish"], "B": ["Baigan bharta", "Biryani"]];

struct dish {
    let Dish : [String]
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.dishtable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    dishtable.dataSource = self
    dishtable.delegate = self
    // Do any additional setup after loading the view.
}


func filterContentForSearchText(searchText: String) {
    // Filter the array using the filter method
    self.Filterval = self.Dishes.filter({( d: dish) -> Bool in
        let DishMatch = (d.Dish == scope)
        let stringMatch = d.Dish.rangeOfString(searchText)
        return DishMatch && (stringMatch != nil)
    })
}

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

func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchScope searchOption: Int) -> Bool {
    self.filterContentForSearchText(self.searchDisplayController!.searchBar.text!)
    return true
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool {
    return true
}

let sections:Array<AnyObject> = ["POPULAR Dishes","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
var usernames = [String]()

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

    let cellID = "cell"

    let cell: UITableViewCell =  self.dishtable.dequeueReusableCellWithIdentifier(cellID) as! UITableViewCell
    println("value : \(indexPath.section)")
    println("value 1: \(indexPath.row)")
     var d : dish
    if tableView == self.searchDisplayController!.searchResultsTableView {

        cell.textLabel!.text = Filterval[sections[indexPath.section] as! String]![indexPath.row]

    } else {

        cell.textLabel!.text = Dishes[sections[indexPath.section] as! String]![indexPath.row]
    }


    return cell

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    println("Dishes section count : \(section)")
    if tableView == self.searchDisplayController!.searchResultsTableView {
        if section == 0 {
            return Filterval["POPULAR Dishes"]!.count
        }
        else if section == 1 {
            return Filterval["A"]!.count
        }
        else if section == 2 {
            return Filterval["B"]!.count
        }
        else if section == 3 {
            return Filterval["C"]!.count
        }
        else if section == 4 {
            return Filterval["D"]!.count
        }
        else if section == 5 {
            return Filterval["E"]!.count
        }
        else if section == 6 {
            return Filterval["F"]!.count
        }
        return 0
    } else {
    if section == 0 {
        return Dishes["POPULAR Dishes"]!.count
    }
    else if section == 1 {
        return Dishes["A"]!.count
    }
    else if section == 2 {
        return Dishes["B"]!.count
    }
    else if section == 3 {
        return Dishes["C"]!.count
    }
    else if section == 4 {
        return Dishes["D"]!.count
    }
    else if section == 5 {
        return Dishes["E"]!.count
    }
    else if section == 6 {
        return Dishes["F"]!.count
    }
    return 0

    }
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int{

    return 27
}

func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

}


func tableView(tableView: UITableView,
    sectionForSectionIndexTitle title: String,
    atIndex index: Int) -> Int{

        return index
}

func tableView(tableView: UITableView,
    titleForHeaderInSection section: Int) -> String?{

        return self.sections[section] as? String
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    tableView.deselectRowAtIndexPath(indexPath, animated: true)

    var ban = ""

    ban = Dishes[sections[indexPath.section] as! String]![indexPath.row]

    println(ban)


}

I have tried the following links online, but unable to implement the search feature.

  1. http://www.ioscreator.com/tutorials/add-search-table-view-tutorial-ios8-swift

  2. http://www.veasoftware.com/tutorials/2015/4/13/search-display-controller-in-swift-xcode-62-ios-82-tutorial

  3. http://www.raywenderlich.com/76519/add-table-view-search-swift

Can someone help me with search bar?


Answer:

I have made the following changes and got the desired output.

I am storing my string array in the Core Data with a flag for POPUlAR FOOD in the Core Data and fetching these details and storing in different arrays according to alphabets.

Created a switch case to show the sections in the table view.

var distinctstring = [String]()
var arr = [String]()
var arrA = [String]()
var arrB = [String]()
var arrC = [String]()
var arrD = [String]()
var arrE = [String]()
var arrF = [String]()
var arrG = [String]()
var arrH = [String]()
var arrI = [String]()
var arrJ = [String]()
var arrK = [String]()
var arrL = [String]()
var arrM = [String]()
var arrN = [String]()
var arrV = [String]()
var arrX = [String]()
var arrZ = [String]()
var arrP = [String]()
var arrO = [String]()
var arrY = [String]()
var arrU = [String]()
var arrT = [String]()
var arrR = [String]()
var arrW = [String]()
var arrQ = [String]()
var arrS = [String]()


var poparr = [String]()
var filteredTableData = [String]()
var resultSearchController = UISearchController()
let collation = UILocalizedIndexedCollation.currentCollation()
    as! UILocalizedIndexedCollation


override func viewDidLoad() {
    super.viewDidLoad()
    var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
    distinctstring.append("POPULAR FoodS")
    var context: NSManagedObjectContext = appDel.managedObjectContext!
    var request = NSFetchRequest(entityName: "Food")
    var request1 = NSFetchRequest(entityName: "Food")
    if var resultsFood = context.executeFetchRequest(request, error: nil) as? [Food]
    {
        //println("\n Food Results in Table view : \(resultsFood)")
        for resultsb in resultsFood
        {

            if (resultsFood.count > 0)
            {
                println("\(resultsb.Food_name) : \(resultsb.popularity) ")

                if (resultsFood.count > 0)
                {
                    var firstchar = resultsb.Food_name.substringToIndex(resultsb.Food_name.startIndex.successor())
                    distinctstring.append(firstchar)
                    println("firstchar : \(firstchar)")
                    switch firstchar {

                        case "A" :

                            arrA.append(resultsb.Food_name)


                        case "B" :

                            arrB.append(resultsb.Food_name)

                        case "C" :

                            arrC.append(resultsb.Food_name)

                        case "D" :

                            arrD.append(resultsb.Food_name)

                        case "E" :

                            arrE.append(resultsb.Food_name)


                        case "F" :

                            arrF.append(resultsb.Food_name)

                        case "G" :


                            arrG.append(resultsb.Food_name)


                        case "H" :

                            arrH.append(resultsb.Food_name)

                        case "I" :

                            arrI.append(resultsb.Food_name)

                        case "J" :

                            arrJ.append(resultsb.Food_name)

                        case "K" :

                            arrK.append(resultsb.Food_name)

                        case "L" :

                            arrL.append(resultsb.Food_name)

                        case "M" :

                            arrM.append(resultsb.Food_name)

                        case "N" :

                            arrN.append(resultsb.Food_name)

                        case "O" :

                            arrO.append(resultsb.Food_name)

                        case "P" :

                            arrP.append(resultsb.Food_name)

                        case "Q" :

                            arrQ.append(resultsb.Food_name)

                        case "R" :

                            arrR.append(resultsb.Food_name)

                        case "S" :

                            arrS.append(resultsb.Food_name)

                        case "T" :

                            arrT.append(resultsb.Food_name)

                        case "U" :

                            arrU.append(resultsb.Food_name)

                        case "V" :

                            arrV.append(resultsb.Food_name)

                        case "W" :

                            arrW.append(resultsb.Food_name)

                        case "X" :

                            arrX.append(resultsb.Food_name)

                        case "Y" :

                            arrY.append(resultsb.Food_name)

                        case "Z" :

                            arrZ.append(resultsb.Food_name)



                        default:
                            println("No present")
                    }
                    arr.append(resultsb.Food_name)
                }
            }
            else
            {
                println("No rows found")

            }

        }
        println("array A = \(arrA)")
        println("array B = \(arrB)")
        println("array C = \(arrC)")
        println("array D = \(arrD)")
        println("array E = \(arrE)")
        println("array F = \(arrF)")
        println("array G = \(arrG)")
        println("array H = \(arrH)")
        println("array I = \(arrI)")
        println("array J = \(arrJ)")
        println("array K = \(arrK)")
        println("array L = \(arrL)")
        println("array M = \(arrM)")
        println("array N = \(arrN)")
        println("array O = \(arrO)")
        println("array P = \(arrP)")
        println("array Q = \(arrQ)")
        println("array R = \(arrR)")
        println("array S = \(arrS)")
        println("array T = \(arrT)")
        println("array U = \(arrU)")
        println("array V = \(arrV)")
        println("array W = \(arrW)")
        println("array X = \(arrX)")
        println("array Y = \(arrY)")
        println("array Z = \(arrZ)")


       distinctstring = uniq(distinctstring)

    }

    if var resultsFood1 = context.executeFetchRequest(request1, error: nil) as? [Food]
    {
        //println("\n Food Results in Table view : \(resultsFood)")
        for resultsb in resultsFood1
        {

            if (resultsFood1.count > 0)
            {

                //println("\n Table view Results ")
                //println("Value of Foodname Array : \(resultsb)")
                if (resultsFood1.count > 0)
                {
                    if (resultsb.popularity == 1)
                    {    println("Value of pop Foodname Array \(resultsb.Food_name) : \(resultsb.popularity) ")
                        poparr.append(resultsb.Food_name)
                    }
                }
            }
            else
            {
                println("No rows found")

            }

        }
        println("poparr = \(poparr)")

    }


    self.Foodtable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")

    Foodtable.dataSource = self
    Foodtable.delegate = self
    //searchBar.delegate = self

    self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()
        controller.searchBar.placeholder = "Search by Food name"
        self.Foodtable.tableHeaderView = controller.searchBar

        return controller
    })()

    // Reload the table
    self.Foodtable.reloadData()
    // Do any additional setup after loading the view.
}



func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // 2
    if (self.resultSearchController.active) {
        return self.filteredTableData.count
    }
    else {



        switch distinctstring[section]
        {

        case "POPULAR FOOD" :

            return self.poparr.count

        case "A" :

            return self.arrA.count


        case "B" :

            return self.arrB.count

        case "C" :

            return self.arrC.count

        case "D" :

            return self.arrD.count

        case "E" :

            return self.arrE.count


        case "F" :

            return self.arrF.count

        case "G" :


            return self.arrG.count


        case "H" :

            return self.arrH.count

        case "I" :

            return self.arrI.count

        case "J" :

            return self.arrJ.count

        case "K" :

            return self.arrK.count

        case "L" :

            return self.arrL.count

        case "M" :

            return self.arrM.count

        case "N" :
            return self.arrN.count
        case "O" :
            return self.arrO.count
        case "P" :
            return self.arrP.count
        case "Q" :
            return self.arrQ.count
        case "R" :
            return self.arrR.count
        case "S" :
            return self.arrS.count
        case "T" :
            return self.arrT.count
        case "U" :
            return self.arrU.count
        case "V" :
            return self.arrV.count
        case "W" :
            return self.arrW.count
        case "X" :
            return self.arrX.count
        case "Y" :
            return self.arrY.count
        case "Z" :
            return self.arrZ.count


        default:

            return self.arr.count

        }

    }
}

func uniq<S: SequenceType, E: Hashable where E==S.Generator.Element>(source: S) -> [E] {
    var seen: [E:Bool] = [:]
    return filter(source) { seen.updateValue(true, forKey: $0) == nil }
}

///////////////////////////////////////Section

func numberOfSectionsInTableView(tableView: UITableView) -> Int {

           return (distinctstring.count)

}


   ///////////////////////////////////////Section

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    tableView.deselectRowAtIndexPath(indexPath, animated: true)

    var dishes = ""
    if (self.resultSearchController.active) {

        dishes = filteredTableData[indexPath.row]


    }
    else {
    println("distinctLetters : \(distinctstring[indexPath.section])")
        switch (distinctstring[indexPath.section]) {


        case "POPULAR FOOD" :

            dishes = poparr[indexPath.row]

        case "A" :

            dishes = arrA[indexPath.row]

        case "B":

            dishes = arrB[indexPath.row]

        case "C":

            dishes = arrC[indexPath.row]

        case "D" :

            dishes = arrD[indexPath.row]

        case "E":

            dishes = arrE[indexPath.row]

        case "F":

            dishes = arrF[indexPath.row]

        case "G" :

            dishes = arrG[indexPath.row]

        case "H":

            dishes = arrH[indexPath.row]

        case "I":

            dishes = arrI[indexPath.row]

        case "J" :

            dishes = arrJ[indexPath.row]

        case "K":

            dishes = arrK[indexPath.row]

        case "L":

            dishes = arrL[indexPath.row]

        case "M" :

            dishes = arrM[indexPath.row]

        case "N":

            dishes = arrN[indexPath.row]

        case "O":

            dishes = arrO[indexPath.row]

        case "P" :

            dishes = arrP[indexPath.row]

        case "Q":

            dishes = arrQ[indexPath.row]

        case "R":

            dishes = arrR[indexPath.row]

        case "S" :

            dishes = arrS[indexPath.row]

        case "T":

            dishes = arrT[indexPath.row]

        case "U":

            dishes = arrU[indexPath.row]

        case "V" :

            dishes = arrV[indexPath.row]

        case "W":

            dishes = arrW[indexPath.row]

        case "X":

            dishes = arrX[indexPath.row]

        case "Y" :

            dishes = arrY[indexPath.row]

        case "Z":

            dishes = arrZ[indexPath.row]
            //return sectionHeaderView
        default:

            dishes = arr[indexPath.row]
        }



    }
    println("row selected : \(dishes)")
}

func tableView(tableView: UITableView,titleForHeaderInSection section: Int) -> String?{

    if (self.resultSearchController.active) {


        return ""
    }
    else {
             return "\(distinctstring[section])"
    }

    }

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

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell;
    cell.textLabel!.font = UIFont(name: "Gotham", size: 13)

    //println("distinctLetters in cell : \(distinctLetters[indexPath.section]) ")
    cell.textLabel!.numberOfLines = 2;
    if (self.resultSearchController.active) {
        cell.textLabel?.text = filteredTableData[indexPath.row]

        return cell
    }
    else {


        switch (distinctstring[indexPath.section]) {

        case "POPULAR FOOD" :

            cell.textLabel?.text = poparr[indexPath.row]
        case "A" :

            cell.textLabel?.text = arrA[indexPath.row]

        case "B":

            cell.textLabel?.text = arrB[indexPath.row]

        case "C":

            cell.textLabel?.text = arrC[indexPath.row]

        case "D" :

            cell.textLabel?.text = arrD[indexPath.row]

        case "E":

            cell.textLabel?.text = arrE[indexPath.row]

        case "F":

            cell.textLabel?.text = arrF[indexPath.row]

        case "G" :

            cell.textLabel?.text = arrG[indexPath.row]

        case "H":

            cell.textLabel?.text = arrH[indexPath.row]

        case "I":

            cell.textLabel?.text = arrI[indexPath.row]

        case "J" :

            cell.textLabel?.text = arrJ[indexPath.row]

        case "K":

            cell.textLabel?.text = arrK[indexPath.row]

        case "L":

            cell.textLabel?.text = arrL[indexPath.row]

        case "M" :

            cell.textLabel?.text = arrM[indexPath.row]

        case "N":

            cell.textLabel?.text = arrN[indexPath.row]

        case "O":

            cell.textLabel?.text = arrO[indexPath.row]

        case "P" :

            cell.textLabel?.text = arrP[indexPath.row]

        case "Q":

            cell.textLabel?.text = arrQ[indexPath.row]

        case "R":

            cell.textLabel?.text = arrR[indexPath.row]

        case "S" :

            cell.textLabel?.text = arrS[indexPath.row]

        case "T":

            cell.textLabel?.text = arrT[indexPath.row]

        case "U":

            cell.textLabel?.text = arrU[indexPath.row]

        case "V" :

            cell.textLabel?.text = arrV[indexPath.row]

        case "W":

            cell.textLabel?.text = arrW[indexPath.row]

        case "X":

            cell.textLabel?.text = arrX[indexPath.row]

        case "Y" :

            cell.textLabel?.text = arrY[indexPath.row]

        case "Z":

            cell.textLabel?.text = arrZ[indexPath.row]
            //return sectionHeaderView
        default:

            cell.textLabel?.text = arr[indexPath.row]
        }

        return cell
    }Food
    //return cell;
}


   func updateSearchResultsForSearchController(searchController: UISearchController)
{
    filteredTableData.removeAll(keepCapacity: false)

    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text)
    let array = (arr as NSArray).filteredArrayUsingPredicate(searchPredicate)
    filteredTableData = array as! [String]

    self.Foodtable.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool {
    return true
}



}

Related:


Parse JSON output from AlamoFire


json,swift,nsurlrequest
I am using the latest Alamofire to manage a GET http request to my server. I am using the following to GET and parse the JSON: Alamofire.request(.GET, "*******") .responseJSON {(request, response, JSON, error) in if let statusesArray = JSON as? NSArray{ if let aStatus = statusesArray[0] as? NSDictionary{ //OUTPUT SHOWN...

Swift timer in milliseconds


xcode,swift
I want to change the timer every millisecond but it doesnt work as expected. NSTimer.scheduledTimerWithTimeInterval(0.001, target: self, selector: Selector("advanceTimer:"), userInfo: nil, repeats: true); func advanceTimer(timer: NSTimer){ self.time += 0.001; let milliseconds = self.time * 100; let remaingMilliseconds = Int((milliseconds % 1000) / 10); let seconds = Int((milliseconds / 1000) %...

iOS 9 not opening Instagram app with URL SCHEME


ios,swift,swift2,ios9
The following URL opens on iOS 8.3 and lower, but it does not work and iOS 9 let instagramURL = NSURL(string: "instagram://app") Why won't the URL open?...

Characters and Strings in Swift


ios,string,swift,unicode,character
Reading the documentation and this answer, I see that I can initialize a Unicode character in either of the following ways: let narrowNonBreakingSpace: Character = "\u{202f}" let narrowNonBreakingSpace = "\u{202f}" As I understand, the second one would actually be a String. And unlike Java, both of them use double quotes...

animating a view on top of uitableview


ios,swift,autolayout
I have a UINavigationController that has my custom ViewController with a tableView in it that takes up the whole screen. I want to push down the tableView and reveal a settings menu with just a couple items. My SettingsView.xib I created in a separate nib that is 320 x 90...

UITapGestureRecognizer sender is the gesture, not the ui object


ios,xcode,swift,uigesturerecognizer
I've got a button called and I gave it a UIGestureRecognizer so that an IBAction is only run when the button is long pressed. You do this by adding a UILongPressGestureRecognizer to the button iteself. Then you control drag that gesture recognizer to a function like this: @IBAction func handleGesture(sender:...

iOS 8 Swift CS193P Calculator Bug Switch Operation


ios,swift
I just started learning Swift with Stanford tutorial. I have Xcode 6.3.2. I'm getting a bug at a switch operation and can't understand how to solve it. I attached a screenshot as well @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddleOfTypingANumber{ enter() } switch operation{ case "➕":...

What is the best practice add video background view?


ios,objective-c,swift,video
I want to add background view with video (or gif) like in app "Uber" I'd like to use video background view for a long time in my app. And I want to know the answers to these questions: What of them will consume less battery energy Can I use it...

iOS: What is the callback when tapped on the empty space between keyboard and search bar to dismiss the keyboard when search bar is active


ios,objective-c,swift
I have SearchController for my TableViewController. I wanted to perform some actions when user taps on the empty space on the screen (between the keyboard and search bar) to dismisses the keyboard and displays the main Table View.

What's the equivalent of finally in Swift


swift,try-catch-finally
I try to use the error handling modeling in Swift2. do { try NSFileManager.defaultManager().removeItemAtPath("path") } catch { // ... } finally { // compiler error. } But it seems that there is no finally keyword out there.How can I achieve try-catch-finally pattern in Swift.Any help is welcome....

Do I have to use both of these methods?


ios,swift,uitableview
When I expand a UITableViewCell on touch, I know I have to update the UITableView. Right now I'm doing: tableView.beginUpdates() tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() Do I need to use both updates methods as well as the reload method? Or is it just one or the other? I'm not completely understanding,...

Unexpectedly found nil while unwrapping an Optional value - Plist


ios,swift,plist
i am trying to read from propriety list using swift but im getting this error, and thats the code im using to read from my plist : Arrays i'm using : var recipeNames :[String] = [] var recipeImages :[String] = [] var recipeTime :[String] = [] In viewDidload : var...

Get NSString from NSMutableArray on Swift


swift,nsmutablearray
How can I get NSString from NSMutableArray created with NSStrings in a for loop? I want to store in one NSString, all elements of NSMutableArray. This is my code: class Persona: NSObject { var edad: Int var altura: Double var nombre: NSString var apellido: NSString var cualidades: NSMutableArray init(edad:Int, altura:Double,...

iOS Swift: Sound not playing on iPhone Simulator


ios,iphone,swift,audio,ios-simulator
In my iOS Swift application, and i am trying to play sound on click of a button. func playSound() { var audioPlayer = AVAudioPlayer() let soundURL = NSBundle.mainBundle().URLForResource("doorbell", withExtension: "mp3") audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil) audioPlayer.play() } I am running the application in iOS iPhone Simulator. I have doorbell.mp3...

PFUser not unwrapped - swift


ios,xcode,swift
I'm beginning to learn swift with parse and i've run into this error: "Value of optional type 'PFUser?' not unwrapped; did you mean to use '!' or '?' I can't seem to get it to work... PFFacebookUtils.logInWithPermissions(["public_profile", "user_about_me", "user_birthday"], block: { user, error in if user == nil { println("the...

Difference between stringByAppendingString and appendString in ios


ios,objective-c,swift,nsstring,nsmutablestring
What is the difference between stringByAppendingString and appendString? If NSString is not mutable then how could it append string?

How to do a “show (e.g Push)” segue programatically without animation?


ios,objective-c,swift,storyboard,segue
How can I do a "show (e.g Push)" segue programatically without animation? None of the solutions I've found works the same way as the one in storyboard.

After an insert into the UITableView : custom the cell


ios,objective-c,uitableview
I'm using insertion into my UITableView with this : Skill * newSkill = [[Skill alloc] init]; newSkill.name = @"Nouvelle compétence"; newSkill.pathPicto = @"generic"; [self.skills insertObject:newSkill atIndex:0]; NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; [self.tableView beginUpdates]; [self.tableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationTop]; [self.tableView endUpdates]; It works great but now I want that the inserted cell be...

Swift Range on the fly 1…12.contains(1) Cannot invoke 'contains' with (Int)


swift,range
Is is not possible to create a range and call its contains method like this: 1...12.contains(1) When I create a var range = 1...12 and print its dynamicType I get a Swift.Range<Swift.Int>, so I'm guessing is not a type mismatch problem, or is it?...

MFMessageComposeViewControllerDelegate not being called


ios,swift
I am trying to implement a class that will present a MFMessageComposeViewController from the AppDelegate. The class declaration looks like this: import UIKit import MessageUI class MyClass: NSObject, MFMessageComposeViewControllerDelegate { func sendAMessage() { // message view controller let messageVC = MFMessageComposeViewController() messageVC.body = "Oh hai!" messageVC.recipients = ["8675309"] // set...

How to code a generic Swift class which stores a Generator of the same type


swift,generics
I'm trying to write a class which handles objects of a homogenous type, and I'd like to feed in those objects using an (otherwise arbitrary) Generator of the same type. In essence this: class MyGenericClass<T> { var source : GeneratorType var itemsProcessed = [ T ]() init(source: GeneratorType) { self.source...

How can I show ONLY the date (and not the time) using NSDateFormatter?


ios,iphone,swift
I think the question is pretty straightforward. I need only the date to appear, and not the time. Couldn't find anything for Swift, so my code is here: cell.date.text = NSDateFormatter.localizedStringFromDate(dates[indexPath.row], dateStyle: .ShortStyle, timeStyle: .ShortStyle) ...

How to save text field value in uicollectionviewcell


swift,uitextfield,uicollectionviewcell
hi i have text field in uicollectionviewcell so what i need it example : when i edit text filed value in row 5 and i done it and go to text filed in row 20 to edit value the collectionview has reloaded and forget value in row 5, so i...

IOS - Adjust cell height based on content


ios,uitableview,autolayout
im trying to build apps that have tableview cell similiar with twitter, there are text and images. My problem is i want to insert the image above the text. While it can be text only. So if there are no image, the text will be in position (0,0). And if...

Obj-C Instance method returning a instanceType called from Swift - Function produces expected type 'UIImage!' error


ios,objective-c,swift
I have this instance method in an existing Obj-C UIImage category: - (UIImage *)applyDarkEffect; I'm trying to call it from a Swift file like so: self.backgroundImageView.image = UIImage.applyDarkEffect(image) But get this compiler error: Function produces expected type 'UIImage!'; did you mean to call it with '()'? ...

How to add checkbox to uicollectionview in swift


swift,checkbox,uicollectionviewcell
some time ago someone already asked this question and a few answers were given but i didn't really understand any of them. So i was wondering if anyone could please write an easy to understand tutorial on how to do the things shown on the image below: http://i.imgur.com/BzIBOkH.jpg?1 I would...

iOS Keyboard “Done” button load action


ios,swift,cocoa-touch
I'm trying to get "Done" button on to load an action, preferably the action that I have for my button. Here's the UITextField declaration let someTextField = UITextField() Trying to add a target to the textField someTextField.addTarget(self, action: "loginActionButton", forControlEvents: .EditingDidEndOnExit) ...

looping variable in swift


swift,for-loop,uiimage
i want to change this variable become looping in swift: var image1 = UIImage(named: "image1") var image2 = UIImage(named: "image2") var image3 = UIImage(named: "image3") var image4 = UIImage(named: "image4") var image5 = UIImage(named: "image5") var image6 = UIImage(named: "image6") var image7 = UIImage(named: "image7") images.append(image1!) images.append(image2!) images.append(image3!) images.append(image4!) images.append(image5!)...

Swift Singleton not Working


swift,singleton
Trying to get a Singleton class going in Swift. I'm not getting any errors, but its also just plain not working properly. Here's the code: // The Singleton class: class DataWarehouse { class var sharedData:DataWarehouse { struct Static { static var onceToken : dispatch_once_t = 0 static var instance :...

Omitting the return type in Swift closures


swift
I'm working through one of the examples at the very handy and colourfully named site here, specifically : func applyMutliplication(value: Int, multFunction: Int -> Int) -> Int { return multFunction(value) } applyMutliplication(2, {value in value * 3 }) Notice that the closure given when calling applyMultiplication() does not specify a...

Can't figure out coder aDecoder: NSCoder


ios,xcode,swift
I'm making an app for archiving books, I'm at the point of hooking up a button to save the data, but I can't get past the initialisation. Here is the error Xcode is giving me : Property 'self.bookStore' not initialised at super.init call. And here is my code : import...

How to get time difference based on GMT on Swift


ios,swift
I am trying to get a time difference based on a GMT time. where at the end of everyday the timer resets to zero. I've tried the below code on the Xcode simulator and every time i change the time on the mac, the difference also changes. how can i...

How can I fix crash when tap to select row after scrolling the tableview?


ios,xcode,swift,uitableview,tableviewcell
I have a table view like this: when the user tap one row, I want uncheck the last row and check the selected row. So I wrote my code like this: (for example my lastselected = 0) func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var lastIndexPath:NSIndexPath = NSIndexPath(forRow: lastSelected, inSection:...

Reference method from different class as curried function


swift,methods,currying
There are two merge methods in RACSignal: - (RACSignal *)merge:(RACSignal *)signal; + (RACSignal *)merge:(id<NSFastEnumeration>)signals; When I write RACSignal.merge it references static method: class func merge(signals: NSFastEnumeration!) -> RACSignal! How to reference object method? I can't write self.merge, because it is in wrapper class and self is not RACSignal....

Beacon / IOS CLLocationManager get current region


ios,swift,cllocationmanager,ibeacon
I'm doing a program who is looking for beacon, I implemented CLLocationManager and my apps works except one point. I'm calling startMonitoringForRegion() in order to get the didEnterRegion/didExitRegion callback. Inside these function I'm doing startRangingBeaconsInRegion()/stopRangingBeaconsInRegion() in order to get precise information when the user is in the beacon area. My...

Why doesn't a UITableView scroll until I have 2 additional rows?


ios,uitableview
Scenario: Embedded UITableView in a standard UIViewController's view. Three (3) 80-pt rows fill the UITableView. Problem: UITableView doesn't scroll until the number of rows > 5. I've tested this by varying the number of displayed rows and attempted to scroll. Three (3) rows fills the UITableView. Four (4) fills but...

Cannot invoke method with argument list of type KeyType in Swift


swift,generics
I am working on custom message dispatcher in Swift. I want to have dispatcher which can: dispatch enums as events or whatever what is Hashable. Every object which implements one protocol might be added as listeners Here is the code: import Foundation protocol EventDispatcherProtocol: class { typealias T: Hashable func...

Parse and Swift Geopoints not saving


swift,parse.com,geopoints
I have tried everything. No matter what my Geopoints will not save when using an actual device with xcode or using the simulator. if signUpError == nil { PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint: PFGeoPoint?, error: NSError?) -> Void in if error == nil { PFUser.currentUser()!.setValue(geoPoint, forKey: "location") } } I am not...

AppleScript (or swift) add hours to time


swift,date,applescript
I'm trying to add 8Hours to a date (from the clipboard) set date1 to the clipboard set newdate to date1 + (8 * hours) display dialog "Purchases were downloaded at " & newdate buttons {"OK"} default button 1 But this is not working as expected, I'm having the error Can’t...

Extra table cells when UITableViewController is embedded into a Container in a UIViewController


ios,swift,uitableview,uiviewcontroller
In order to customize a table view and add some additional controls to it, I've embedded a UTTableViewController into a Container View and placed that container View into a UIViewController. I've followed the instructions I found here: Embedding TableView in TableViewController into another view TableView is configured with four static...

It is possible to continuously update the UILabel text as user enter value in UITextField in iOS


ios,objective-c,swift,uitextfield,uilabel
In my application i have one UILabel and UITextField. Initially UILabel text in nil. As soon as user enter some text in UITextField my UILabel text also Update. Let say When user enter A in UITextField my UILabel immediately show A, B in UITextField my UILabel show B and so...

Implementing Applovin Ads with Swift & SpriteKit


ios,swift,applovin
I would like some help with integrating interstitial ads from Applovin using Swift. Currently, I have managed to successfully integrate the SDK and initialize it using ALSdk.initializeSdk(). I have a folder in my project directory called Applovin which contains: headers folder (with all the .h files inside) and libApplovinSdk.a. I...

How to create UITableViewCells with complex content in order to keep scrolling fluent


ios,swift,uitableview,cocoa-touch,ios-charts
I am working on a project where I have a table view which contains a number of cells with pretty complex content. It will be between usually not more than two, but in exceptions up to - lets say - 30 of them. Each of these complex cells contain a...

Build error after I localized Info.plist


ios,objective-c,xcode,swift,localization
I localized Info.plist : And I got this build error : error: could not read data from '/Users/cherif/Apps/Wesh/Info.plist': The file “Info.plist” couldn’t be opened because there is no such file. Actually there are now two Info.plist files : fr.lproj/Info.plist Base.lproj/Info.plist How to localize the Info.plist path ?...

try to recover views from custom cell


ios,uitableview
I made a custom cell from my storyboard, with an UIImageView and a UILabel. Each of them have a tag 100 for the imageView and 102 for UILabel. I try to get them in my datasource method but as below, they are still nil and I don't know why. ...

How to disable the Copy/Hide feature in UIImagePickerController when long pressing a image …?


ios,swift,ios8,uiimagepickercontroller,ios8.3
- Actually am using UIImagePickerController for my usecase,and if i long press any picture ,it shows Copy/Hide option (as shown in the sample image) - I dont want the Copy/Hide feature. Guide me with some suggestions if u too have encountered :)... Thanks in advance...iOS Geeks...PLZ refer my code snippet...