Post

Replies

Boosts

Views

Activity

All of my programmatically created buttons work except for one
I have 10 programmatically buttons create, they all work except for the first.for image in 1...10 {       let imageName = String("image\(String(image)).png")       let imageToDisplay = UIImage(named: imageName)       let catagoryButton = UIButton(type: UIButton.ButtonType.custom) as UIButton       catagoryButton.setBackgroundImage(imageToDisplay, for: .normal)               let xCoor = 20 + 60 * CGFloat(image - 1)       contentWidth += 60               catagoryButton.frame = CGRect(x: xCoor, y: 10, width: 40, height: 40)       catagoryButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)       catagoryButton.tag = image       catagoryScrollView.addSubview(catagoryButton)       print("This Buttons tag is \(catagoryButton.tag)")     }     catagoryScrollView.contentSize = CGSize(width: contentWidth + 20, height: 60) The button action works fine for all of the other buttons, but just incase it just checks for the sender.tag and does a different action depending on the sender. @objc func buttonAction(sender: UIButton!) {     print("button number \(sender.tag)")           var showThisArray = [CreditCard]()     var showThisArrayOfValues = [Double]()           if sender.tag == 1 {       showThisArray = restaurantCards       showThisArrayOfValues = restaurantCardsValues       cardReward = "Restaurants"     }           else if sender.tag == 2 {       showThisArray = gasCards       showThisArrayOfValues = gasCardsValues       cardReward = "Gas Stations"     }           else if sender.tag == 3 {       showThisArray = hotelCards       showThisArrayOfValues = hotelCardsValues       cardReward = "Hotels"     }           else if sender.tag == 4 {       showThisArray = groceryCards       showThisArrayOfValues = groceryCardsValues       cardReward = "Grocery Stores"     }           else if sender.tag == 5 {       showThisArray = transitCards       showThisArrayOfValues = transitCardsValues       cardReward = "Transit Station"     }           else if sender.tag == 6 {       showThisArray = wholesaleCards       showThisArrayOfValues = wholesaleCardsValues       cardReward = "Wholesalers"     }           else if sender.tag == 7 {       showThisArray = drugStoreCards       showThisArrayOfValues = drugStoreCardsValues       cardReward = "Drug Stores"     }           else if sender.tag == 8 {       showThisArray = entertainmentCards       showThisArrayOfValues = entertainmentCardsValues       cardReward = "Entertainment Locations"     }             else if sender.tag == 9 {       showThisArray = supplyCards       showThisArrayOfValues = supplyCardsValues       cardReward = "Supply Stores"     }           else if sender.tag == 10 {       showThisArray = departmentCards       showThisArrayOfValues = departmentCardsValues       cardReward = "Department Stores"     }     else if sender.tag == 11 {       showThisArray = otherCards       showThisArrayOfValues = otherCardValues       cardReward = "Other Categories"     } // More code that is not important } I cannot figure out the root of the problem and I need all of the buttons to work
4
0
600
Jul ’20
JSON Data 'The data couldn’t be read because it isn’t in the correct format'
I am trying to get json data from a site that I created and no matter what I do it says... "The data couldn’t be read because it isn’t in the correct format" The JSON is... { 	"creditCards": [ 		{ 		"issuer": "american express", 		"name": "gold card", 		"numericCode": "3717", 		"image": "", 		"rewards": [ 		{ 				"value": "4.0", 				"reward": "restaurants" 		}, 		{ 				"value": "4.0", 				"reward": "grocery stores" 		} 		] 		}, 		{ "issuer": "american express", 		"name": "cash magnet", 		"numericCode": "", 		"image": "", 		"rewards": [ 		{ 				"value": "1.5", 				"reward": "all" 		} 		] 		}, 		 		{ "issuer": "american express", 		"name": "green card", 		"numericCode": "", 		"image": "", 		"rewards": [ 		{ 				"value": "3.0", 				"reward": "restaurants" 		}, 		{ 				"value": "3.0", 				"reward": "transit" 		} 		] 		}, 		 		{ "issuer": "american express", 		"name": "blue cash everyday", 		"numericCode": "375987", 		"image": "", 		"rewards": [ 		{ 				"value": "3.0", 				"reward": "grocery stores" 		}, 		{ 				"value": "2.0", 				"reward": "gas stations" 		} /* More credit cards that have the same JSON syntax */ ] } And my code for getting the JSON is... guard let url = URL(string: "my_url_that_works") else {             print("URL Failed")             return         }         print("url (\(url)) passed!")         var request = URLRequest(url: url)         request.httpMethod = "GET"                  URLSession.shared.dataTask(with: request) { (data, response, error) in             if let err = error {                 print(err.localizedDescription)                 return             }                          print("data: \(data!)")             print("response: \(response!)")                          do {                 print("Time to get JSON")                 guard let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [NSDictionary] else {                     print("error: \(error?.localizedDescription)")                     return                 }                 print(json["creditCards"]) /* This prints the error above */             } catch {                 print(error.localizedDescription)             }         }.resume() I have done a lot of research into how to solve this and none of the things I do seem to work. I would really appreciate some yelp.
0
0
2.1k
Aug ’20
“Unrecognized selector sent to instance” when calling UIButton.addTarget in a class
Hi! I am trying to create a DropDownMenu class, but when I try to call addTarget to a UIButton this error comes up... 'unrecognized selector sent to instance 0x7fd167f06120' terminating with uncaught exception of type NSException' I have been looking for the answer for hours now, and even on Stack Overflow, no one seems to have the answer. Any help is appreciated! Here is the code for my DropDownMenu class...class DropDownMenu: UIView { var main: UIButton! = UIButton(frame: CGRect(x: 0, y: 0, width: 46, height: 30)) var view: UIView! 	var buttonTitles: [String]! = [""] var titleColor: UIColor! = UIColor.black var font: UIFont! = UIFont.systemFont(ofSize: 18) var buttonsBorderWidth: CGFloat! = 0 var buttonsBorderColor: UIColor? = UIColor.white var buttonsCornerRadius: CGFloat! = 0 var color: UIColor! = UIColor.clear var buttonsImageEdgeInsets: UIEdgeInsets? = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) var images: [UIImage]? = nil var target: UIViewController! private var currentSelected: String? = nil private var optionsStack = UIStackView() init(main: UIButton) { self.main = main super.init(frame: CGRect()) } func createDropDownMenu() { main.addTarget(target, action: #selector(DropDownMenu.openDropdown(:)), for: .touchUpInside) print("Button Target?: \(main.allTargets), self.target: \(String(describing: target))") let mainFrame = main.frame optionsStack.frame = CGRect(x: mainFrame.minX, y: mainFrame.maxY, width: mainFrame.width, height: CGFloat(buttonTitles.count) * mainFrame.height) optionsStack.axis = .vertical view.addSubview(optionsStack) var y: CGFloat! = 0 for title in buttonTitles { let button = UIButton(frame: CGRect(x: 0, y: y, width: mainFrame.width, height: mainFrame.height)) button.setTitle(title, for: .normal) button.setTitleColor(titleColor, for: .normal) button.backgroundColor = color button.titleLabel?.font = font button.addTarget(target, action: #selector(DropDownMenu.onclick), for: .touchUpInside) y += mainFrame.height optionsStack.addArrangedSubview(button) } for button in optionsStack.arrangedSubviews { button.isHidden = true button.alpha = 0 } } @objc private func openDropdown( sender: UIButton) { print("sender: \(String(describing: sender))") optionsStack.arrangedSubviews.forEach { (button) in UIView.animate(withDuration: 0.7) { button.isHidden = !button.isHidden button.alpha = button.alpha == 0 ? 1 : 0 self.view.layoutIfNeeded() } } } @objc private func onclick(_ sender: UIButton) { let title = sender.titleLabel!.text print(title as Any) main.setTitle(title, for: .normal) optionsStack.arrangedSubviews.forEach { (button) in UIView.animate(withDuration: 0.7) { button.isHidden = true button.alpha = 0 } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } Here is the code for the creation of the object in ViewContorller... let main = UIButton(frame: CGRect(x: 50, y: 300, width: 80, height: 30)) main.layer.borderWidth = 1 main.setTitle("Grade", for: .normal) main.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) main.setTitleColor(UIColor.black, for: .normal) let gradeDP = DropDownMenu(main: main) gradeDP.buttonTitles = ["Title 1", "Title 2", "Title 3"] gradeDP.color = UIColor.gray gradeDP.target = self gradeDP.titleColor = UIColor.white gradeDP.view = infoBox This is all of my code...
8
0
13k
Nov ’20