Fixing “use of unresolved identifier 'addTarget'” while adding func to button click eventAdd custom button to navigation controller without borderHow to get the id of button & implementing touchesMoved Simultaneously?add label to UIButtons in iCarouselDo you have to call removeTarget on UIButton?addTarget for button in tableViewAssign 'action' dynamically in uibutton.addTargetUIButton: Click sound when Button is clicked in swiftAdding multiple UIButtons to an UIView with a selector actionaddTarget on UIButton not workingHow to pass a Parameter to the addTarget method of button in swift

What does "Scientists rise up against statistical significance" mean? (Comment in Nature)

A social experiment. What is the worst that can happen?

Is there a way to get `mathscr' with lower case letters in pdfLaTeX?

Does the Linux kernel need a file system to run?

When were female captains banned from Starfleet?

What is the highest possible scrabble score for placing a single tile

Limits and Infinite Integration by Parts

Does Doodling or Improvising on the Piano Have Any Benefits?

Non-trope happy ending?

Keeping a ball lost forever

Pre-mixing cryogenic fuels and using only one fuel tank

Biological Blimps: Propulsion

Creepy dinosaur pc game identification

Calculating total slots

Open a doc from terminal, but not by its name

Why can Carol Danvers change her suit colours in the first place?

What is the English pronunciation of "pain au chocolat"?

Did arcade monitors have same pixel aspect ratio as TV sets?

Do the primes contain an infinite almost arithmetic progression?

Why is this estimator biased?

Can the US President recognize Israel’s sovereignty over the Golan Heights for the USA or does that need an act of Congress?

Redundant comparison & "if" before assignment

Hero deduces identity of a killer

Why should universal income be universal?



Fixing “use of unresolved identifier 'addTarget'” while adding func to button click event


Add custom button to navigation controller without borderHow to get the id of button & implementing touchesMoved Simultaneously?add label to UIButtons in iCarouselDo you have to call removeTarget on UIButton?addTarget for button in tableViewAssign 'action' dynamically in uibutton.addTargetUIButton: Click sound when Button is clicked in swiftAdding multiple UIButtons to an UIView with a selector actionaddTarget on UIButton not workingHow to pass a Parameter to the addTarget method of button in swift













-1















I've created a UIButton programmatically as shown below:



let buttons: [UIButton] = [UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))];


Now if I try to add a function to it programmatically like this:



[buttons[0] addTarget:self action:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside]


I get an error saying that addTarget is not defined.
How do I fix this?










share|improve this question



















  • 1





    Why is this tagged swift?

    – Rakesha Shastri
    Mar 7 at 4:06






  • 1





    Your first line is swift, and your second line is in Objective-C syntax - is this deliberate?

    – Chris Shaw
    Mar 7 at 4:06











  • @ChrisShaw It's not deliberate I just made a silly mistake :P

    – user11140694
    Mar 8 at 9:20















-1















I've created a UIButton programmatically as shown below:



let buttons: [UIButton] = [UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))];


Now if I try to add a function to it programmatically like this:



[buttons[0] addTarget:self action:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside]


I get an error saying that addTarget is not defined.
How do I fix this?










share|improve this question



















  • 1





    Why is this tagged swift?

    – Rakesha Shastri
    Mar 7 at 4:06






  • 1





    Your first line is swift, and your second line is in Objective-C syntax - is this deliberate?

    – Chris Shaw
    Mar 7 at 4:06











  • @ChrisShaw It's not deliberate I just made a silly mistake :P

    – user11140694
    Mar 8 at 9:20













-1












-1








-1








I've created a UIButton programmatically as shown below:



let buttons: [UIButton] = [UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))];


Now if I try to add a function to it programmatically like this:



[buttons[0] addTarget:self action:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside]


I get an error saying that addTarget is not defined.
How do I fix this?










share|improve this question
















I've created a UIButton programmatically as shown below:



let buttons: [UIButton] = [UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))];


Now if I try to add a function to it programmatically like this:



[buttons[0] addTarget:self action:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside]


I get an error saying that addTarget is not defined.
How do I fix this?







ios uibutton addtarget






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 11 at 16:21









E_net4

12.6k73872




12.6k73872










asked Mar 7 at 4:00







user11140694














  • 1





    Why is this tagged swift?

    – Rakesha Shastri
    Mar 7 at 4:06






  • 1





    Your first line is swift, and your second line is in Objective-C syntax - is this deliberate?

    – Chris Shaw
    Mar 7 at 4:06











  • @ChrisShaw It's not deliberate I just made a silly mistake :P

    – user11140694
    Mar 8 at 9:20












  • 1





    Why is this tagged swift?

    – Rakesha Shastri
    Mar 7 at 4:06






  • 1





    Your first line is swift, and your second line is in Objective-C syntax - is this deliberate?

    – Chris Shaw
    Mar 7 at 4:06











  • @ChrisShaw It's not deliberate I just made a silly mistake :P

    – user11140694
    Mar 8 at 9:20







1




1





Why is this tagged swift?

– Rakesha Shastri
Mar 7 at 4:06





Why is this tagged swift?

– Rakesha Shastri
Mar 7 at 4:06




1




1





Your first line is swift, and your second line is in Objective-C syntax - is this deliberate?

– Chris Shaw
Mar 7 at 4:06





Your first line is swift, and your second line is in Objective-C syntax - is this deliberate?

– Chris Shaw
Mar 7 at 4:06













@ChrisShaw It's not deliberate I just made a silly mistake :P

– user11140694
Mar 8 at 9:20





@ChrisShaw It's not deliberate I just made a silly mistake :P

– user11140694
Mar 8 at 9:20












3 Answers
3






active

oldest

votes


















1














you are try to use the Objective-C syntax in swift, this is entirely wrong, use your code as like



 buttons.first?.addTarget(self, action: #selector(self.buttonClicked(_:)), for: .touchUpInside)


and handle the action as like



 @objc func buttonClicked( _ sender: UIButton) 
print("buttonClicked Action Found")




Ref : Apple Document for UIButton






share|improve this answer

























  • @SrikanthEswaran - dont think so, if you r new in iOS, it will happens always.

    – Anbu.Karthik
    Mar 7 at 8:38


















0














Changes following code:




...



 buttons[0].addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)


...



@objc func buttonClicked(_ button: UIButton) 

button.setTitle("Clicked", for: .normal)






share|improve this answer






























    0














    First of all you are creating [UIButton] which is Array of UIButton and it's not a single Button.



    You can not create Array of UIButton that way. You will need a for loop for that and you need to update the frame accordingly.



    And you can create a single UIButton this way:



    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))


    then you can add it into the UIView this way:



    self.view.addSubview(button)


    Without above line it your button will not show into your screen.



    Next if you want to add action to that button you can do it by adding this line in your button code:



    button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)


    and it will need a helper method which will execute when button will click.



    @objc func buttonClicked(_ sender: UIButton) 
    //Perform your action when button is clicked.



    And you also need to apply backgroundColor and setTitle to the button.



    and your final code will look like:



    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
    button.backgroundColor = UIColor.green
    button.setTitle("Test Button", for: .normal)
    button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
    self.view.addSubview(button)





    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55035853%2ffixing-use-of-unresolved-identifier-addtarget-while-adding-func-to-button-cl%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown
























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      you are try to use the Objective-C syntax in swift, this is entirely wrong, use your code as like



       buttons.first?.addTarget(self, action: #selector(self.buttonClicked(_:)), for: .touchUpInside)


      and handle the action as like



       @objc func buttonClicked( _ sender: UIButton) 
      print("buttonClicked Action Found")




      Ref : Apple Document for UIButton






      share|improve this answer

























      • @SrikanthEswaran - dont think so, if you r new in iOS, it will happens always.

        – Anbu.Karthik
        Mar 7 at 8:38















      1














      you are try to use the Objective-C syntax in swift, this is entirely wrong, use your code as like



       buttons.first?.addTarget(self, action: #selector(self.buttonClicked(_:)), for: .touchUpInside)


      and handle the action as like



       @objc func buttonClicked( _ sender: UIButton) 
      print("buttonClicked Action Found")




      Ref : Apple Document for UIButton






      share|improve this answer

























      • @SrikanthEswaran - dont think so, if you r new in iOS, it will happens always.

        – Anbu.Karthik
        Mar 7 at 8:38













      1












      1








      1







      you are try to use the Objective-C syntax in swift, this is entirely wrong, use your code as like



       buttons.first?.addTarget(self, action: #selector(self.buttonClicked(_:)), for: .touchUpInside)


      and handle the action as like



       @objc func buttonClicked( _ sender: UIButton) 
      print("buttonClicked Action Found")




      Ref : Apple Document for UIButton






      share|improve this answer















      you are try to use the Objective-C syntax in swift, this is entirely wrong, use your code as like



       buttons.first?.addTarget(self, action: #selector(self.buttonClicked(_:)), for: .touchUpInside)


      and handle the action as like



       @objc func buttonClicked( _ sender: UIButton) 
      print("buttonClicked Action Found")




      Ref : Apple Document for UIButton







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Mar 7 at 4:35

























      answered Mar 7 at 4:24









      Anbu.KarthikAnbu.Karthik

      63.2k17123112




      63.2k17123112












      • @SrikanthEswaran - dont think so, if you r new in iOS, it will happens always.

        – Anbu.Karthik
        Mar 7 at 8:38

















      • @SrikanthEswaran - dont think so, if you r new in iOS, it will happens always.

        – Anbu.Karthik
        Mar 7 at 8:38
















      @SrikanthEswaran - dont think so, if you r new in iOS, it will happens always.

      – Anbu.Karthik
      Mar 7 at 8:38





      @SrikanthEswaran - dont think so, if you r new in iOS, it will happens always.

      – Anbu.Karthik
      Mar 7 at 8:38













      0














      Changes following code:




      ...



       buttons[0].addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)


      ...



      @objc func buttonClicked(_ button: UIButton) 

      button.setTitle("Clicked", for: .normal)






      share|improve this answer



























        0














        Changes following code:




        ...



         buttons[0].addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)


        ...



        @objc func buttonClicked(_ button: UIButton) 

        button.setTitle("Clicked", for: .normal)






        share|improve this answer

























          0












          0








          0







          Changes following code:




          ...



           buttons[0].addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)


          ...



          @objc func buttonClicked(_ button: UIButton) 

          button.setTitle("Clicked", for: .normal)






          share|improve this answer













          Changes following code:




          ...



           buttons[0].addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)


          ...



          @objc func buttonClicked(_ button: UIButton) 

          button.setTitle("Clicked", for: .normal)







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 7 at 4:28









          Hồ Minh TườngHồ Minh Tường

          1




          1





















              0














              First of all you are creating [UIButton] which is Array of UIButton and it's not a single Button.



              You can not create Array of UIButton that way. You will need a for loop for that and you need to update the frame accordingly.



              And you can create a single UIButton this way:



              let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))


              then you can add it into the UIView this way:



              self.view.addSubview(button)


              Without above line it your button will not show into your screen.



              Next if you want to add action to that button you can do it by adding this line in your button code:



              button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)


              and it will need a helper method which will execute when button will click.



              @objc func buttonClicked(_ sender: UIButton) 
              //Perform your action when button is clicked.



              And you also need to apply backgroundColor and setTitle to the button.



              and your final code will look like:



              let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
              button.backgroundColor = UIColor.green
              button.setTitle("Test Button", for: .normal)
              button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
              self.view.addSubview(button)





              share|improve this answer





























                0














                First of all you are creating [UIButton] which is Array of UIButton and it's not a single Button.



                You can not create Array of UIButton that way. You will need a for loop for that and you need to update the frame accordingly.



                And you can create a single UIButton this way:



                let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))


                then you can add it into the UIView this way:



                self.view.addSubview(button)


                Without above line it your button will not show into your screen.



                Next if you want to add action to that button you can do it by adding this line in your button code:



                button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)


                and it will need a helper method which will execute when button will click.



                @objc func buttonClicked(_ sender: UIButton) 
                //Perform your action when button is clicked.



                And you also need to apply backgroundColor and setTitle to the button.



                and your final code will look like:



                let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                button.backgroundColor = UIColor.green
                button.setTitle("Test Button", for: .normal)
                button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
                self.view.addSubview(button)





                share|improve this answer



























                  0












                  0








                  0







                  First of all you are creating [UIButton] which is Array of UIButton and it's not a single Button.



                  You can not create Array of UIButton that way. You will need a for loop for that and you need to update the frame accordingly.



                  And you can create a single UIButton this way:



                  let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))


                  then you can add it into the UIView this way:



                  self.view.addSubview(button)


                  Without above line it your button will not show into your screen.



                  Next if you want to add action to that button you can do it by adding this line in your button code:



                  button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)


                  and it will need a helper method which will execute when button will click.



                  @objc func buttonClicked(_ sender: UIButton) 
                  //Perform your action when button is clicked.



                  And you also need to apply backgroundColor and setTitle to the button.



                  and your final code will look like:



                  let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                  button.backgroundColor = UIColor.green
                  button.setTitle("Test Button", for: .normal)
                  button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
                  self.view.addSubview(button)





                  share|improve this answer















                  First of all you are creating [UIButton] which is Array of UIButton and it's not a single Button.



                  You can not create Array of UIButton that way. You will need a for loop for that and you need to update the frame accordingly.



                  And you can create a single UIButton this way:



                  let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))


                  then you can add it into the UIView this way:



                  self.view.addSubview(button)


                  Without above line it your button will not show into your screen.



                  Next if you want to add action to that button you can do it by adding this line in your button code:



                  button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)


                  and it will need a helper method which will execute when button will click.



                  @objc func buttonClicked(_ sender: UIButton) 
                  //Perform your action when button is clicked.



                  And you also need to apply backgroundColor and setTitle to the button.



                  and your final code will look like:



                  let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                  button.backgroundColor = UIColor.green
                  button.setTitle("Test Button", for: .normal)
                  button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
                  self.view.addSubview(button)






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 7 at 6:34









                  rmaddy

                  245k27324388




                  245k27324388










                  answered Mar 7 at 5:38









                  DharmeshDharmesh

                  51.7k23128151




                  51.7k23128151



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55035853%2ffixing-use-of-unresolved-identifier-addtarget-while-adding-func-to-button-cl%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                      Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                      Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved