Alvin Varghese Alvin Varghese - 6 months ago 3x
Swift Question

Check UIButton already exists or not in Swift

I found Objective-C coding for this topic. But the problem is that most of the classes and functions in Objective-C is deprecated in swift programming language.

I am using a UIButton inside a UITableView with

flagForAction[Boolean Value]
. So what i want to achieve is that if the UIButton is created once , there is no need to recreate it. So for that i need to check whether the UIButton already exists or not. Somebody suggested me the concept of tag for this, applying a particular tag to this UIButton and checking that is exist on the view or not. But i don't know how to do that.


I am using view as example. You can also identify a button with accessibilityIdentifier property of the button, if you dont want to use tag proprerty of button. For example :

    var button = UIButton(frame: CGRectMake(0, 0, 100, 44))
    button.accessibilityIdentifier = "button 1"

Here, i created a button with accessibilityIdentifier "button 1"

While creating the next button, i will check in the subview if it contains the button with accessibilityIdentifier "button 1", as below

    var subviews : NSArray = self.view.subviews
    for button : AnyObject in subviews{

        if(button .isKindOfClass(UIButton)){

            if(button.accessibilityIdentifier == "button 1"){

                println("Button Already Exists")
                println("Create new button")