Alvin Varghese
Alvin Varghese

Reputation: 822

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.

Upvotes: 0

Views: 2808

Answers (3)

Max
Max

Reputation: 2299

in swift 2.0

for view in myview.subviews {

      if let btn : UIButton = view as? UIButton {
           // access button here, either tag or title etc..
      }

 }

Upvotes: 0

ikuramedia
ikuramedia

Reputation: 6058

Setting a tag:

myButton.tag = 1234 // some unique value, probably better to define as an enum or constant

Retrieving a view by tag (likely in cellForRowAtIndexPath):

if let myButton = tableviewCell.viewWithTag(1234) { // change tableviewCell for whatever your tableview cell variable name is
    // myButton already existed
} else {
    // TableviewCell doesn't contain a myButton, so create one here and set the tag as above
}

Upvotes: 3

iOS
iOS

Reputation: 5480

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"
    self.view.addSubview(button)

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")
            }else{
                println("Create new button")

            }
        }
    }

Upvotes: -1

Related Questions