UIButton not highlighting or running code when clicked - swift

I'm setting up 26 buttons, adding them as subviews to a letterButtonLabel, and appending them to an letterButtons array.
for row in 0..<6 {
for column in 0..<5 {
if row == 5 && column > 0 { continue }
let letterButton = UIButton(type: .system)
letterButton.titleLabel?.font = UIFont.systemFont(ofSize: 36)
letterButton.setTitle("O", for: .normal)
letterButton.addTarget(self, action: #selector(letterTapped), for: .touchUpInside)
let frame = CGRect(x: width * column, y: height * row, width: width, height: height)
letterButton.frame = frame
letterButtonLabel.addSubview(letterButton)
letterButtons.append(letterButton)
}
}
Afterwards, I assign a letter to each button using the letterButtons array.
var index = 0
for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
letterButtons[index].setTitle("\(letter)", for: .normal)
index += 1
}
I then manually add layout constraints.
Here is the functionality for each button:
#objc func letterTapped(_ sender: UIButton) {
// check the letter and react
sender.isHidden = true
guard let word = currentWord else { return }
guard var charactersArray = currentWordField.text?.components(separatedBy: "") else { return }
guard let originalCurrentWordField = currentWordField.text else { return }
for (index, letter) in word.enumerated() {
let strLetter = String(letter)
if strLetter == sender.titleLabel?.text {
charactersArray[index] = strLetter
}
}
currentWordField.text = charactersArray.joined()
if currentWordField.text == originalCurrentWordField {
livesLeft -= 1
}
if wordBank.contains(word) {
// you got it! reset letters
level += 1
let ac = UIAlertController(title: "Good job!", message: nil, preferredStyle: .alert)
let action = UIAlertAction(title: "Continue", style: .default, handler: resetForNextLevel)
ac.addAction(action)
present(ac, animated: true)
}
if livesLeft == 0 {
let ac = UIAlertController(title: "Game Over", message: nil, preferredStyle: .alert)
let action = UIAlertAction(title: "Restart", style: .default, handler: resetForNextLevel)
ac.addAction(action)
present(ac, animated: true)
}
}
(adding all just in case)
My button doesn't highlight or click. Is there anything here that might explain the problem? I'm curious about common mistakes.

UILabel has by default userInteractionEnabled = false.
Setting this to true should fix your problem

Related

In Swift 5, How to execute actions successively in UIAlert?

I have created an alert Where a mybutton have to be hidden while the activity indicator has to be shown. but it didn't work.
Here is the code:
private func showAlert() {
let alert = UIAlertController(title: "aaaaaa", message: ccccccccc, preferredStyle: .alert)
let attributedString = NSAttributedString(string: "aaaaa", attributes: [.font: UIFont.boldSystemFont(ofSize: 18), //your font here
.foregroundColor : Theme.bleu!])
alert.setValue(attributedString, forKey: "attributedTitle")
alert.addAction(UIAlertAction(title: annuler, style: .cancel))
alert.addAction(UIAlertAction(title: optimiserLesMicrosUniquement, style: .default, handler: { (action) in
self.myButton.isHidden = true // Here begins the problem
self.activityIndicator.isHidden = false
let menuOptimiser = functionNumberX()
self.activityIndicator.isHidden = true // Here is the problem
self.myButton.isHidden = false
let reponse = menuOptimiser.0
if reponse == false {
self.showAlerteMenuOptimal()
} else {
if menuOptimiser.1 > 0 {
self.presentAlerteDuGain(gain: menuOptimiser.1, menu: menuOptimiser.2)
} else {
self.presentAlerteOptimisationSansGainDeCalories(calorie: abs((round(menuOptimiser.1))), menu: menuOptimiser.2)
}
}
self.gestionDeLaNotationDuMenuEnCours()
}))
present(alert, animated: true)
}
When i execute it, mybutton never disappears, and activity indicator never appears.
i don't know how to do that.
try removing, these two lines , since you are opposite at almost the same time .
self.activityIndicator.isHidden = true // Here is the problem
self.myButton.isHidden = false
I just found a solution. Here is the code
var menuOptimiser : (Bool, Float, [[AlimentObject]])!
private func showAlert() {
let alert = UIAlertController(title: "aaaaaa", message: ccccccccc, preferredStyle: .alert)
let attributedString = NSAttributedString(string: "aaaaa", attributes: [.font: UIFont.boldSystemFont(ofSize: 18), //your font here
.foregroundColor : Theme.bleu!])
alert.setValue(attributedString, forKey: "attributedTitle")
alert.addAction(UIAlertAction(title: annuler, style: .cancel))
alert.addAction(UIAlertAction(title: optimiserLesMicrosUniquement, style: .default, handler: { (action) in
self.myButton.isHidden = true // Here begins the problem
self.activityIndicator.isHidden = false
DispatchQueue.main.asyncAfter(deadline: .now()) {
let menuOptimiser = functionNumberX()
self.activityIndicator.isHidden = true // Here is the problem
self.myButton.isHidden = false
let reponse = menuOptimiser.0
if reponse == false {
self.showAlerteMenuOptimal()
} else {
if menuOptimiser.1 > 0 {
self.presentAlerteDuGain(gain: menuOptimiser.1, menu: menuOptimiser.2)
} else {
self.presentAlerteOptimisationSansGainDeCalories(calorie: abs((round(menuOptimiser.1))), menu: menuOptimiser.2)
}
}
}
self.gestionDeLaNotationDuMenuEnCours()
}))
present(alert, animated: true)
}

Set title label of two action sheet buttons

when i choose an option from action sheet, it set a title label to button. But when i click another button with another action sheet, it cancel title label of first button. How can i set each button without cancel any title label?
This is how it works:
This is my code of two action sheets:
#IBAction func paymentMethodActionSheet(_ sender: Any) {
PaymentMethodTitle.titleLabel?.text = "Seleziona"
let optionMenu = UIAlertController(title: nil, message: "Scegli il metodo di pagamento", preferredStyle: .actionSheet)
let cardAction = UIAlertAction(title: "Paga con carta", style: .default, handler: { action in
self.PaymentMethodTitle.titleLabel?.text = "Paga con carta"
self.PaymentMethodTitle.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.right
})
let contantiAction = UIAlertAction(title: "Contanti", style: .default, handler: { action in
self.PaymentMethodTitle.titleLabel?.text = "Contanti"
self.PaymentMethodTitle.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.right
})
let cancelAction = UIAlertAction(title: "Cancella", style: .cancel)
optionMenu.addAction(cardAction)
optionMenu.addAction(contantiAction)
optionMenu.addAction(cancelAction)
if let popoverController = optionMenu.popoverPresentationController {
popoverController.barButtonItem = sender as? UIBarButtonItem
popoverController.sourceView = self.view
popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popoverController.permittedArrowDirections = []
}
self.present(optionMenu, animated: true, completion: nil)
}
#IBAction func shippingMethodActionSheet(_ sender: Any) {
shippingMethodTitle.titleLabel?.text = "Seleziona"
let option2Menu = UIAlertController(title: nil, message: "Scegli l'opzione d'acquisto", preferredStyle: .actionSheet)
let houseAction = UIAlertAction(title: "Consegna a domicilio", style: .default, handler: { action in
self.shippingMethodTitle.titleLabel?.text = "Consegna a domicilio"
self.shippingMethodTitle.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.right
})
let businessAction = UIAlertAction(title: "Ritiro presso attività", style: .default, handler: { action in
self.shippingMethodTitle.titleLabel?.text = "Ritiro presso attività"
self.shippingMethodTitle.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.right
})
let cancel2Action = UIAlertAction(title: "Cancella", style: .cancel)
option2Menu.addAction(houseAction)
option2Menu.addAction(businessAction)
option2Menu.addAction(cancel2Action)
if let popoverController2 = option2Menu.popoverPresentationController {
popoverController2.barButtonItem = sender as? UIBarButtonItem
popoverController2.sourceView = self.view
popoverController2.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popoverController2.permittedArrowDirections = []
}
self.present(option2Menu, animated: true, completion: nil)
}
Instead of using self.PaymenMethodTitle?.titleLabel.text = "Contanti"to change the button title inside closure, just Use self.PaymentMethodTitle.setTitle("Contanti", for: .normal).
I've tried it myself and Its working Fine.
Code:
class ViewController: UIViewController {
#IBOutlet weak var btn1: UIButton!
#IBOutlet weak var btn2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func btn1Pressed(_ sender: Any) {
let optionMenu = UIAlertController(title: nil, message: "Scegli il metodo di pagamento", preferredStyle: .actionSheet)
let cardAction = UIAlertAction(title: "Paga con carta", style: .default, handler: { action in
self.btn1.setTitle("Paga con carta", for: .normal)
self.btn1.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.right
})
let contantiAction = UIAlertAction(title: "Contanti", style: .default, handler: { action in
self.btn1.setTitle("Conati", for: .normal)
self.btn1.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.right
})
let cancelAction = UIAlertAction(title: "Cancella", style: .cancel)
optionMenu.addAction(cardAction)
optionMenu.addAction(contantiAction)
optionMenu.addAction(cancelAction)
if let popoverController = optionMenu.popoverPresentationController {
popoverController.barButtonItem = sender as? UIBarButtonItem
popoverController.sourceView = self.view
popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popoverController.permittedArrowDirections = []
}
self.present(optionMenu, animated: true, completion: nil)
}
#IBAction func btn2Pressed(_ sender: Any) {
let option2Menu = UIAlertController(title: nil, message: "Scegli l'opzione d'acquisto", preferredStyle: .actionSheet)
let houseAction = UIAlertAction(title: "Consegna a domicilio", style: .default, handler: { action in
self.btn2.setTitle("Consegna a domicilio", for: .normal)
self.btn2.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.right
})
let businessAction = UIAlertAction(title: "Ritiro presso attività", style: .default, handler: { action in
self.btn2.setTitle("Ritiro presso attività", for: .normal)
self.btn2.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.right
})
let cancel2Action = UIAlertAction(title: "Cancella", style: .cancel)
option2Menu.addAction(houseAction)
option2Menu.addAction(businessAction)
option2Menu.addAction(cancel2Action)
if let popoverController2 = option2Menu.popoverPresentationController {
popoverController2.barButtonItem = sender as? UIBarButtonItem
popoverController2.sourceView = self.view
popoverController2.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popoverController2.permittedArrowDirections = []
}
self.present(option2Menu, animated: true, completion: nil)
}
}
Simulator ScreenShot:

Enable copy button title on long press on the button

I have UIButton for an address in my tableview cell. When I tap on it once; I open google map with the direction no problem. Now, I want to provide the option for long gesture so if you hold your finger on the button, it provides the option to copy the address which is in the title of the button. This is my code:
#IBOutlet weak var addressBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
addLongPressGesture()
}
#objc func longPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizer.State.began {
// how do I make it possible to copy the title of the button here? The address is already inserted as the title of the button
}
}
func addLongPressGesture(){
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
longPress.minimumPressDuration = 0.5
self.addressBtn.addGestureRecognizer(longPress)
}
This is where on one tap it goes to the map with no problem; so I have no issue here but just fyi:
#IBAction func addressClicked(_ sender: Any) {
if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {
let street = order.street.replacingOccurrences(of: " ", with: "+")
let postalCode = order.postalCode.replacingOccurrences(of: " ", with: "+")
if street == "" || order.city == "" || order.province == "" || postalCode == ""{
UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=\(order.longitude),\(order.latitude)&directionsmode=driving")! as URL)
} else {
UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=+\(street),+\(order.city),+\(order.province),+\(postalCode)&directionsmode=driving")! as URL)
}
} else {
NSLog("Can't use comgooglemaps://")
}
}
Use
let text = addressBtn.currentTitle
or
let text = addressBtn.titleLabel?.text
I figured it out with the following code:
//Create the AlertController and add Its action like button in Actionsheet
let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheetControllerIOS8.view.tintColor = AppColors.Blue
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { _ in
}
actionSheetControllerIOS8.addAction(cancelActionButton)
let saveActionButton = UIAlertAction(title: "Open Google Map", style: .default)
{ _ in
if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {
let street = order.street.replacingOccurrences(of: " ", with: "+")
let postalCode = order.postalCode.replacingOccurrences(of: " ", with: "+")
if street == "" || order.city == "" || order.province == "" || postalCode == ""{
UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=\(order.longitude),\(order.latitude)&directionsmode=driving")! as URL)
} else {
UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=+\(street),+\(order.city),+\(order.province),+\(postalCode)&directionsmode=driving")! as URL)
}
} else {
NSLog("Can't use comgooglemaps://")
}
}
actionSheetControllerIOS8.addAction(saveActionButton)
let deleteActionButton = UIAlertAction(title: "Copy Address", style: .default)
{ _ in
let address = "\(order.street), \(order.city), \(order.province), \(order.postalCode)"
let pasteBoard = UIPasteboard.general
pasteBoard.string = address
}
actionSheetControllerIOS8.addAction(deleteActionButton)
self.present(actionSheetControllerIOS8, animated: true, completion: nil)
}

Programed textfile&Labels with CoreData -Swift3

I'm using CoreData and I have an issue.
So, I'm using scroll view and in the following code it adds a label and a textfield every time the user presses the "add" button. And I need to save this to CoreData(yes it needs to be CoreData). But how can I do this? I went through CoreData relationships but couldn't understand and hoping for help.
Thank you vary much :)
var count = 0
#IBAction func add(_ sender: Any) {
count += 1
let myPoint = count * 100
if count >= 1 {
let myAlartController = UIAlertController(title: "Add Item", message: "Please add title and context", preferredStyle: UIAlertControllerStyle.alert)
myAlartController.addTextField(configurationHandler: ({(firstText: UITextField!) -> Void in firstText.placeholder = "Please add title"}))
myAlartController.addTextField(configurationHandler: ({(secondText: UITextField!) -> Void in secondText.placeholder = "Please add context"}))
let okButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
(action: UIAlertAction) -> Void in
//When the bottum is pressed
let myCGRect = CGRect(x: 0, y: 0, width: 105, height: 30)
//Label
let myLabel = UILabel(frame: myCGRect)
myLabel.backgroundColor = UIColor.orange
let labelOfAlert = myAlartController.textFields?[0]
myLabel.text = labelOfAlert?.text
myLabel.textColor = UIColor.white
myLabel.layer.position = CGPoint(x: 60, y: (565 + myPoint))
//textFiled
let myTextField = UITextField(frame: myCGRect)
myTextField.backgroundColor = UIColor.gray
let textOfAlert = myAlartController.textFields?[1]
myTextField.text = textOfAlert?.text
myTextField.layer.position = CGPoint(x: 135, y: (565 + myPoint))
self.labelTopConstrain.constant = (CGFloat(900 + myPoint))
self.labelBottomConstrain.constant = 20
self.myScroll.layoutIfNeeded()
myLabel.tag = self.count
myTextField.tag = self.count
self.myScroll.addSubview(myLabel)
self.myScroll.addSubview(myTextField)
let testSave = Test(context: myContext)
testSave.label = myLabel.text
testSave.textField = myTextField.text
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)
myAlartController.addAction(okButton)
myAlartController.addAction(cancelAction)
present(myAlartController, animated: true, completion: nil)
}/*if*/
}/**/

How to put large chunk of code in AlertController block (Swift)

In my collection view cell, I have a button which successfully saves the current user (PFUser) to an array of users of each event (which are the objects at index path).
However, I would like to add an alert view, but have been unsuccessful in putting the enormous chunk of code inside the alert action block. I suppose I could create another method but I feel there's a simpler way to do it.
When I tried putting it in, A. the sheer number of brackets threw me off a bit and B. it didn't recognize "alertController" anymore at the bottom of the method.
Thanks for the help like always.
func buttonTapped(sender: AnyObject) {
let button = sender as! UIButton
let view = button.superview
let cell = view?.superview as! EventCell
let indexPath = collectionView.indexPathForCell(cell)
// print(indexPath)
if let indexPath = indexPath {
if let event = events?[indexPath.row] {
//pops alert vc
var alertController : UIAlertController = UIAlertController(title: event.eventTitle, message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
let saveUserToEvent = UIAlertAction(title: "Yes", style: .Default) { _ in
// WHAT TO DO HERE? I want to add the stuff below
}
alertController.addAction(saveUserToEvent)
var attendees = [String]()
if let attendeesTmp = event["attendees"] as?[String] {
attendees = attendeesTmp;
}
if let objId = PFUser.currentUser()?.objectId {
var found = false
for objIdd in attendees {
if objIdd == objId {
found = true
break;
}
}
if !found {
attendees.append(objId)
event["attendees"] = attendees;
event.saveInBackground()
}
}
if let user = PFUser.currentUser() {
var eventsAttending = [String]()
if let eventsAttendingTmp = user["eventsToAttend"] as?[String] {
eventsAttending = eventsAttendingTmp;
}
if let eventId = event.objectId {
var found = false
for eventIdd in eventsAttending {
if eventIdd == eventId {
found = true
break;
}
}
if !found {
eventsAttending.append(eventId)
user["eventsToAttend"] = eventsAttending;
user.saveInBackground()
}
}
}
}
}
}
Did you put
alertController.addAction(saveUserToEvent)
In the brackets as well? It stays outside.
This should work
func buttonTapped(sender: AnyObject) {
let button = sender as! UIButton
let view = button.superview
let cell = view?.superview as! UITableViewCell
let indexPath = collectionView.indexPathForCell(cell)
// print(indexPath)
if let indexPath = indexPath {
if let event = events?[indexPath.row] {
//pops alert vc
var alertController : UIAlertController = UIAlertController(title: event.eventTitle, message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
let saveUserToEvent = UIAlertAction(title: "Yes", style: .Default) { _ in
var attendees = [String]()
if let attendeesTmp = event["attendees"] as?[String] {
attendees = attendeesTmp;
}
if let objId = PFUser.currentUser()?.objectId {
var found = false
for objIdd in attendees {
if objIdd == objId {
found = true
break;
}
}
if !found {
attendees.append(objId)
event["attendees"] = attendees;
event.saveInBackground()
}
}
if let user = PFUser.currentUser() {
var eventsAttending = [String]()
if let eventsAttendingTmp = user["eventsToAttend"] as?[String] {
eventsAttending = eventsAttendingTmp;
}
if let eventId = event.objectId {
var found = false
for eventIdd in eventsAttending {
if eventIdd == eventId {
found = true
break;
}
}
if !found {
eventsAttending.append(eventId)
user["eventsToAttend"] = eventsAttending;
user.saveInBackground()
}
}
}
}
alertController.addAction(saveUserToEvent)
}
}
}