I'm trying to control what happens when the view background is tapped.
The view has a field, a button and a list collectionView.
When the user enters a name into the field, the button is enabled and when the button is tapped the name from the field is saved into a list collectionView.
What I want to happen:
If the field isFirstResponder when the viewBackGround is tapped then I want the superView_Tapped() to be triggered.
If the collectionView is tapped it works fine.
If the view background is tapped it works fine.
When the view backGround is tapped the field text is cleared and sone other things take place. See superView_Tapped() below.
What actually happens:
The problem I'm having is that tapping the button also triggers the superView_Tapped().
So what happens is the field is emptied and a row is inserted into the collection view with no name.
The part of the reason is that the superView_Tapped() is fired first and then the button code fires after.
Is there a way to exclude the button tap from triggering the superView_Tapped()?
let tap = UITapGestureRecognizer(target: self, action: #selector(self.superView_Tapped))
tap.numberOfTapsRequired = 1
tap.delegate = self
tap.cancelsTouchesInView = false
self.view.addGestureRecognizer(tap)
@objc func superView_Tapped()
{
if insertFld.isFirstResponder
{
insertFld.resignFirstResponder()
insertFld.text = ""
insertButton.isEnabled = false
// print("They emptied the fld when editing", gItemID)
gItemID = 0
insertButton.filled_Red_Back(title: K.Titles.add_Btn)
theOriginal_Text = ""
}
}
@IBAction func insertButton_Tapped(_ sender: UIButton)
{
if current_Item_ID != 0
{
update()
} else {
insertRow()
}
}
func update()
{
let theItemName = insertFld.text
do {
try dbQueue_GRDB.write { db in
try db.execute(sql: "UPDATE " + theTable + " SET Item_Name = :item_Name WHERE ItemID = :id",
arguments: ["item_Name": theItemName, "id": current_Item_ID])
}
applySnapshot()
clean_Up()
if ModelData.getTheConfirmation_Bool()
{
sendConfirmationAlert(theTitle: "Updated", theMessage: nil, buttonTitle: K.Titles.ok)
}
} catch {
let theString = "\(error)"
if theString.contains("UNIQUE constraint failed")
{
sendConfirmationAlert(theTitle: K.Titles.itemAlreadyExists, theMessage: nil, buttonTitle: K.Titles.ok)
} else {
print("Updating list failed! \(VC_String) \(error)")
}
}
}
func insertRow()
{
let insertName = insertFld.text?.trimmingCharacters(in: .whitespaces)
do {
try dbQueue_GRDB.write { db in
try db.execute(sql: "INSERT INTO " + theTable + " (Item_Name,Practice,Training,Practice_Log) VALUES (?,?,?,?)",
arguments: [insertName,"false","",""])
}
if ModelData.getTheConfirmation_Bool()
{
sendConfirmationAlert(theTitle: "Row Created", theMessage: nil, buttonTitle: K.Titles.ok)
}
applySnapshot()
clean_Up()
} catch {
let theString = "\(error)"
if theString.contains("UNIQUE constraint failed")
{
sendConfirmationAlert(theTitle: K.Titles.itemAlreadyExists, theMessage: nil, buttonTitle: K.Titles.ok)
} else {
print("Inserting to list failed! \(VC_String) \(error)")
}
}
}
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I have an app that was written in UIKit. It's too large, and it would be much too time consuming at this point to convert it to SwiftUI.
I want to incorporate the new limited contacts into this app. The way it's currently written everything works fine except for showing the limited contacts in the contact picker.
I have downloaded and gone though the Apple tutorial app but I'm having trouble thinking it through into UIKit. After a couple of hours I decided I need help.
I understand I need to pull the contact IDs of the contacts that are in the limited contacts list. Not sure how to do that or how to get it to display in the picker. Any help would be greatly appreciated.
func requestAccess(completionHandler: @escaping (_ accessGranted: Bool) -> Void)
{
switch CNContactStore.authorizationStatus(for: .contacts)
{
case .authorized:
completionHandler(true)
case .denied:
showSettingsAlert(completionHandler)
case .restricted, .notDetermined:
CNContactStore().requestAccess(for: .contacts) { granted, error in
if granted
{
completionHandler(true)
} else {
DispatchQueue.main.async { [weak self] in
self?.showSettingsAlert(completionHandler)
}
}
}
// iOS 18 only
case .limited:
completionHandler(true)
@unknown default: break
}
}
// A text field that displays the name of the chosen contact
@IBAction func contact_Fld_Tapped(_ sender: TextField_Designable)
{
sender.resignFirstResponder()
// The contact ID that is saved to the Db
getTheCurrentContactID()
let theAlert = UIAlertController(title: K.Titles.chooseAContact, message: nil, preferredStyle: .actionSheet)
// Create a new contact
let addContact = UIAlertAction(title: K.Titles.newContact, style: .default) { [weak self] _ in
self?.requestAccess { _ in
let openContact = CNContact()
let vc = CNContactViewController(forNewContact: openContact)
vc.delegate = self // this delegate CNContactViewControllerDelegate
DispatchQueue.main.async {
self?.present(UINavigationController(rootViewController: vc), animated: true)
}
}
}
let getContact = UIAlertAction(title: K.Titles.fromContacts, style: .default) { [weak self] _ in
self?.requestAccess { _ in
self?.contactPicker.delegate = self
DispatchQueue.main.async {
self?.present(self!.contactPicker, animated: true)
}
}
}
let editBtn = UIAlertAction(title: K.Titles.editContact, style: .default) { [weak self] _ in
self?.requestAccess { _ in
let store = CNContactStore()
var vc = CNContactViewController()
do {
let descriptor = CNContactViewController.descriptorForRequiredKeys()
let editContact = try store.unifiedContact(withIdentifier: self!.oldContactID, keysToFetch: [descriptor])
vc = CNContactViewController(for: editContact)
} catch {
print("Getting contact to edit failed: \(self!.VC_String) \(error)")
}
vc.delegate = self // delegate for CNContactViewControllerDelegate
self?.navigationController?.isNavigationBarHidden = false
self?.navigationController?.navigationItem.hidesBackButton = false
self?.navigationController?.pushViewController(vc, animated: true)
}
}
let cancel = UIAlertAction(title: K.Titles.cancel, style: .cancel) { _ in }
if oldContactID.isEmpty
{
editBtn.isEnabled = false
}
theAlert.addAction(getContact) // Select from contacts
theAlert.addAction(addContact) // Create new contact
theAlert.addAction(editBtn) // Edit this contact
theAlert.addAction(cancel)
let popOver = theAlert.popoverPresentationController
popOver?.sourceView = sender
popOver?.sourceRect = sender.bounds
popOver?.permittedArrowDirections = .any
present(theAlert,animated: true)
}
func requestAccess(completionHandler: @escaping (_ accessGranted: Bool) -> Void)
{
switch CNContactStore.authorizationStatus(for: .contacts)
{
case .authorized:
completionHandler(true)
case .denied:
showSettingsAlert(completionHandler)
case .restricted, .notDetermined:
CNContactStore().requestAccess(for: .contacts) { granted, error in
if granted
{
completionHandler(true)
} else {
DispatchQueue.main.async { [weak self] in
self?.showSettingsAlert(completionHandler)
}
}
}
// iOS 18 only
case .limited:
completionHandler(true)
@unknown default: break
}
}
// MARK: - Contact Picker Delegate
extension AddEdit_Quote_VC: CNContactPickerDelegate
{
func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact)
{
selectedContactID = contact.identifier
let company: String = contact.organizationName
let companyText = company == "" ? K.Titles.noCompanyName : contact.organizationName
contactNameFld_Outlet.text = CNContactFormatter.string(from: contact, style: .fullName)!
companyFld_Outlet.text = companyText
save_Array[0] = K.AppFacing.true_App
setSaveBtn_AEQuote()
}
}
extension AddEdit_Quote_VC: CNContactViewControllerDelegate
{
func contactViewController(_ viewController: CNContactViewController, shouldPerformDefaultActionFor property: CNContactProperty) -> Bool
{
return false
}
func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?)
{
selectedContactID = contact?.identifier ?? ""
if selectedContactID != ""
{
let company: String = contact?.organizationName ?? ""
let companyText = company == "" ? K.Titles.noCompanyName : contact!.organizationName
contactNameFld_Outlet.text = CNContactFormatter.string(from: contact!, style: .fullName)
companyFld_Outlet.text = companyText
getTheCurrentContactID()
if selectedContactID != oldContactID
{
save_Array[0] = K.AppFacing.true_App
setSaveBtn_AEQuote()
}
}
dismiss(animated: true, completion: nil)
}
}
I have a number of apps which use a custom tab-bar for navigation. The tab-bar uses buttons with an ICON on top and text below. I have this working in Xcode 12.5 with an extension similar to those below. I wanted to see if I could convert to Xcode 13 and take advantage of the new button configurations. I was having some problems getting this to work properly so I did the following testing.
I created a new empty project in Xcode 12.5.1. Closed and re-opened the app in Xcode 13 and added two plain buttons. I didn’t change any of the attributes in the IB so they just have a blue button text. Then I attached one of the extensions below to each button. When the app opens in iSO 15 the buttons display the correct style. However, when either of the buttons is tapped the display reverts back to the text attributes of the button in the IB. So it’s blue, the text reads button and the text size changes back to the default. The ICON and the positioning remain unchanged.
If I create a new Xcode 13 project and do the exact same thing then everything working fine. Is anybody else seeing this? Is there something I need to change something in the extensions to make it work in pre 13 Xcode?
@available(iOS 15.0, *)
extension UIButton
{
func settings_MenuBtn()
{
self.configuration = .plain()
let imageConfig = UIImage.SymbolConfiguration(scale: .large)
self.configuration?.title = "Settings"
self.configuration?.attributedTitle?.foregroundColor = .white
self.configuration?.imagePlacement = .top
self.configuration?.titleAlignment = .center
self.configuration?.imagePadding = 6
self.configuration?.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)
self.configuration?.image = UIImage(systemName: "gearshape", withConfiguration: imageConfig)
self.configuration?.attributedTitle?.font = .systemFont(ofSize: gMenuTextSize, weight: .regular)
}
}
@available(iOS 15.0, *)
extension UIButton.Configuration
{
static func settings_MenuBtn2() -> UIButton.Configuration
{
let imageConfig = UIImage.SymbolConfiguration(scale: .large)
var config: UIButton.Configuration = .plain()
config.title = "Settings"
config.attributedTitle?.foregroundColor = .white
config.attributedTitle?.font = .systemFont(ofSize: gMenuTextSize, weight: .regular)
config.image = UIImage(systemName: "gearshape", withConfiguration: imageConfig)
config.imagePlacement = .top
config.titleAlignment = .center
config.imagePadding = 6
config.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)
return config
}
}
When I execute a restore on my in-app purchase I'm getting a warning, however the restore is successfully executed. I think this is something new with Xcode 14.3. My test device is running iOS 16.4
This is the warning:
<SKPaymentQueue: 0x283708a80>: No observers found that respond to "paymentQueue:shouldAddStorePayment:forProduct:", will not check for purchase intents
It fires at this point in the code. If I comment out the first line, I don't get the warning however, the restore doesn't execute. Is anybody else seeing this or do I have something wrong in my code? I know it's only a warning but any help would be appreciated.
@IBAction func restoreButtonTapped(_ sender: UIBarButtonItem)
{
SKPaymentQueue.default().add(self)
SKPaymentQueue.default().restoreCompletedTransactions()
}
I've included the rest of the code just for a completeness.
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction])
{
for transaction in transactions
{
switch transaction.transactionState
{
case .purchasing:
//print("Purchase in progress...")
break
case .purchased:
//print("Purchase Successful")
SKPaymentQueue.default().finishTransaction(transaction)
//print("Transaction Complete")
// Hide the restore button
navigationItem.setRightBarButton(nil, animated: true)
//Set the BaseVerion in the Db to true
IAPHandler.set_BaseVersion_To_Purchased()
//Also hide the Purchase button
UIView.animate(withDuration: 1.0, animations: { [weak self] in
self?.purchaseButton.alpha = 0
}) { [weak self] (success) in
self?.selector_Top_Constraint.constant = 30
}
case .failed:
if let error = transaction.error
{
let errorDescription = error.localizedDescription
print("Transaction failed due to error: \(errorDescription)")
}
case .restored:
SKPaymentQueue.default().finishTransaction(transaction)
//print("Transaction Complete")
// Hide the restore button
navigationItem.setRightBarButton(nil, animated: true)
// Set the BaseVerion in the Db to true
IAPHandler.set_BaseVersion_To_Purchased()
// Also hide the Purchase button
UIView.animate(withDuration: 1.0, animations: { [weak self] in
self?.purchaseButton.alpha = 0
}) { [weak self] (success) in
self?.selector_Top_Constraint.constant = 30
}
case .deferred:
//print("Purchase Deferred")
break
@unknown default:
if let error = transaction.error
{
let errorDescription = error.localizedDescription
print("Transaction failed due to error: \(errorDescription)")
}
break
}
}
}
@IBAction func purchaseButtonTapped(_ sender: UIButton)
{
let theAlert = UIAlertController.init(title: K.Titles.pleaseChoose, message: nil, preferredStyle: .actionSheet)
let theCancleAction = UIAlertAction(title: K.Titles.cancel, style: .cancel)
let thePurchaseAction = UIAlertAction(title: K.DefaultList_Buttons.purchase_BaseVersion_Btn, style: .default) { [weak self] (action2) in
if SKPaymentQueue.canMakePayments()
{
// User can make payments
let paymentRequest = SKMutablePayment()
paymentRequest.productIdentifier = self!.base_Product_ID
SKPaymentQueue.default().add(self!)
SKPaymentQueue.default().add(paymentRequest)
} else {
// User cannot make payments
print("User cannot make payments")
}
}
theAlert.addAction(thePurchaseAction)
theAlert.addAction(theCancleAction)
theAlert.setValue(NSAttributedString(string: theAlert.title ?? "", attributes: [.font : UIFont.systemFont(ofSize: (gDefaultTextSize - 2), weight: UIFont.Weight.semibold)]), forKey: "attributedTitle")
let popOver = theAlert.popoverPresentationController
popOver?.sourceView = sender
popOver?.sourceRect = sender.bounds
popOver?.permittedArrowDirections = .any
present(theAlert, animated: true)
}
I have this code in the sceneDelegate of my app. I understand that .main is going to be deprecated. The warning says to use view?.window?.windowScene?.screen but there is no view in sceneDelegate. How can I change
let screenSize = UIScreen.main.fixedCoordinateSpace.bounds
to not use .main?
Thanks in advance.
invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debugI get this warning when I tap either of the switches shown below. I've tried capturing the switch state in a var and using that to trigger the do/catch statement but no joy. I've even tried pulling the do/catch into separate functions and I still get the warning. Has anybody else run into this and how did you fix it?@IBAction func greetingFormat_Tapped(_ sender: UISwitch)
{
let theQuery = theTable_Settings.filter(settingID == 1)
if sender.isOn
{
do {
if try Database.shared.databaseConnection!.run(theQuery.update(greeting_Format <- "true")) > 0
{
greetingFormatLabel_Outlet.text = NSLocalizedString("HelloMrSmith_String", comment: "")
} else {
print("greeting format true not found")
}
} catch {
print("greeting format true update failed! Error: \(error)")
}
} else {
do {
if try Database.shared.databaseConnection!.run(theQuery.update(greeting_Format <- "false")) > 0
{
greetingFormatLabel_Outlet.text = NSLocalizedString("HiJoe_String", comment: "")
} else {
print("greeting format false not found")
}
} catch {
print("greeting format false update failed! Error: \(error)")
}
}
}@IBAction func nonrefundableSwitch_Tapped(_ sender: UISwitch)
{
let theQuery = theTable_Settings.filter(settingID == 1)
var itsOn: String = ""
if sender.isOn
{
itsOn = "true"
} else {
itsOn = "false"
}
if itsOn == "true"
{
do {
if try Database.shared.databaseConnection!.run(theQuery.update(nonRefundable_Bool <- "true")) > 0
{
depositDueLabel_Outlet.text = NSLocalizedString("nonRefunddepositisdue_String", comment: "")
} else {
print("nonRefundable true not found")
}
} catch {
print("nonRefundable true update failed! Error: \(error)")
}
} else {
do {
if try Database.shared.databaseConnection!.run(theQuery.update(nonRefundable_Bool <- "false")) > 0
{
depositDueLabel_Outlet.text = NSLocalizedString("depositisdue_String", comment: "")
} else {
print("nonRefundable false not found")
}
} catch {
print("nonRefundable false update failed! Error: \(error)")
}
}
}