Swift best practice: How to keep track of different objects? - swift

I'm wondering what is a good solution to keep track of different objects of same type.
I have this function:
private extension MenuButtonsViewController {
// TODO: Find a way to find correct button based on MenuItem
func buttonFor(for menuItem: MenuItem) -> EmojiButton? {
guard let subViews = stackView.subviews as? [EmojiButton] else {
return nil
}
let button = buttonFactory.makeEmojiButton(title: menuItem.icon)
for subView in subViews where subView == button {
return subView
}
return nil
}
}
I have an array (UIStackView) with a varying number of buttons (EmojiButton). The buttons are created with content from MenuItem.
I'm looking for a good and clean solution how to find and remove a particular button from the stackView array, based on a MenuItem.
So far I had three ideas:
To create a new object, initalized with same values as the one to remove, and then match using ==. (Solution above). This didn't work.
To add an id to all buttons, and then a corresponding id to the MenuItem object. But this doesn't seem like an elegant solution to have to add that everywhere, and expose this variable from the button object.
Maybe store the button in a wrapper class (like MenuItemButton) with an id to match to, or by storing the MenuItem object so I can match against that.
Any ideas? How is this usually done?

If MenuItem and EmojiButton inherit from UIView, you can make use of the tag property that is available on all UIView's.
You first need to assign a unique tag value to each of your MenuItem's.
You then need to assign this same value to the corresponding Emoji button's tag property. (This would be a good thing to do in your factory.)
Having done that, you can modify your function as follows:
//assumes MenuItem and EmojiButton inherit from UIView
func buttonFor(for menuItem: MenuItem) -> EmojiButton? {
return stackView.viewWithTag(menuItem.tag) as? EmojiButton
}

Related

Is there a way to pass functions into views as optional parameters?

I am making an application in SwiftUI that involves answering yes or no questions. Because of this I have created a subview call YesOrNoView. This subview has two buttons, one labeled yes and the other labeled no. The view accepts a binding variable of question that returns true or false based on the users answer. It also accepts a binding variable of questionsAnswered and increments it whenever either button is pressed. This behavior works for most questions in the game, but for the final question I want it to execute custom logic to take the user to a different view. To do this I am trying to make the view accept a custom action/method that I can call from either buttons action logic. Ideally, the action would also be optional so that I don't have to pass it in the 99% percent of the time when I'm not using it.
How do I pass a function as an optional parameter into a view and then run that action when a button within said view is pressed?
I tried adding actions using
struct YesOrNoView<Content: Action>: View {
...
but it couldn't find action or Action within it's scope.
I also tried using
struct YesOrNoView<Content>: View {
But I got an error saying that the Content variables type could not be inferred.
Any help would be greatly appreciated.
It return clickAction back to the view
struct GenericButton<Title: StringProtocol>: View {
let title: Title
let action: () -> Void
var body: some View {
Button(action: action) {
Text(title)
}.frame(width: 200, height: 40)
}
}
}
Usage:
GenericButton("Button") {
// Button tapped action
}
I managed to figure it out with help from #JoakimDanielson. The trick is to pass in an empty function as the default.
var myFunction: () -> Void = {}
Thanks for the help everyone.

Looping through entities which describe what action should be taken on screen after keypresses

Please forgive me if I don't describe this question too well, I am new to programming MacOS apps using Swift. I know the way I'm going about this is probably wrong and I just need someone to tell me the right way.
My main app screen
I have a Core Data application that stores an ordered list of entities called Items. These Items are intended to describe a single step in an activity that describes what should happen on screen. If you know the Mac application QLab each Item is like a single cue in QLab.
I have created an Activity class that is designed to read through each Item to determine the Item type and it's related information. Once the Item type has been determined the Activity class needs to present a View with information related to that particular Item and then wait until the user presses the right arrow key to then proceed to the next Item in the Core Data store where the process repeats until all Items have been read. Each time a new Item is read in the loop, the information on the screen should change after the user presses the right arrow each time.
The problem is that I don't know exactly how the best way of going about this should be programatically speaking. I have the code that retrieves the array of Items as an NSFetchRequest:
let moc = (NSApplication.shared.mainWindow?.contentViewController?.representedObject as! NSPersistentDocument).managedObjectContext!
let fetchRequest : NSFetchRequest = Item.fetchRequest()
do {
let items = try moc.fetch(fetchRequest)
print("Found " + String(items.count) + " items to use in the activity.")
for item in items {
print(item.itemType)
// How do I pause this loop for a user keypress after using data from this Item to display?
}
} catch {
print("Error retrieving Items")
}
I can retrieve the keydown event using NSEvent.addLocalMonitorForEvents(matching: .keyDown) and I'm also able to create View Controllers to display the information on a second screen. I just don't know how I should create the 'main loop', so to speak, so that information is displayed and then the app waits until the user presses a key to proceed...
I can share my project code if more information is needed and many thanks to anyone who can enlighten me... :)
You could try using a NSPageController. In your NSPageController you add a ContainerView which will display the ViewControllers that display information for each item. Each ViewController will need a storyboard identifier, e.g. ViewControllerItem1.
Your NSPageController class must conform to the NSPageControllerDelegate protocol and contains an array of ViewControllers to display.
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
arrangedObjects = ["ViewControllerItem1", "ViewControllerItem2", "...","ViewControllerItemN" ]
}
Note about arrangedObjects from the NSPageController documentation: An array containing the objects displayed in the page controller’s view.
Then you implement NSPageControllers viewControllerForIdentifier to return the ViewController that you currently want to display in the ContainerView.
func pageController(_ pageController: NSPageController, viewControllerForIdentifier identifier: String) -> NSViewController {
switch identifier {
case "ViewControllerItem1":
return mainStoryboard().instantiateController(withIdentifier:"ViewControllerItem1") as? ViewControllerItem1
case "...":
default:
}
}
In your action handler for the key down event you implement.
self.navigateForward(sender) or self.navigateBack(sender)
I also implemented this method but I don't remember whether it was required.
func pageControllerDidEndLiveTransition(_ pageController: NSPageController) {
self.completeTransition()
}

comboBoxSelectionDidChange with multiple NScomboboxes

I have an app with two combo boxes in the same view that is both loaded from an SQLite database. If the user makes a selection in combo box 1, I want to fire a method to restrict the values in combo box 2.
I think I need comboBoxSelectionDidChange function, but I don't know how to tell whether the function has been fired by a selection in combo box 1 or 2?
Have looked at the function parameters but can't see how I can tell which combo box fired the function?
The notification contains an object which represents the NSComboBox instance.
If you have created an NSComboBox outlet
#IBOutlet weak var firstComboBox : NSComboBox!
you can compare the instance with the notification object
func comboBoxSelectionDidChange(_ notification: Notification) {
let comboBox = notification.object as! NSComboBox
if comboBox == firstComboBox {
// do something with firstComboBox
} else {
// it's another comboBox
}
}
The solution for ascertaining which combobox fired the selectionDidChange method worked fine. One thing I did learn though was that the method is fired before .stringValue for the new selection is updated. I wanted to use the new .stringValue in the selectionDidChange method but discovered the previous .stringValue.
The way I got around this was to use the indexOfSelectedItem which is updated before the selectionDidChange method is fired.
So my code became
//In order to be able to restrict the contacts available when a company is selected use the comboboSelectionDidChange function
func comboBoxSelectionDidChange(_ notification: Notification) {
//Define a constant combobox that takes the notification object and casts it as an NSCombobox
let combobox = notification.object as! NSComboBox
//Can now test on the combobox object because we only want to do something if cmbCompany selection changes
if combobox == cmbCompany {
//The issue with comboboSelectionDidChange function is that the method is fired before the .stringValue is updated. So using .stringValue wont work as it will use the .stringValue from previous selected item. Therefore use index of selected item as this is updated before the comboboSelectionDidChange function is fired
//Define index which is the index of the newly selected item
let index = cmbCompany.indexOfSelectedItem
//Because the compIndex index will be the same as the index of the selected item we can get the newly selected company from the compIndex which is used to populate the cmbCombobox
let company = compIndex[index]
//Get the idCompany from combobox selection passing in the company from the new selection
idcom = (delegate as! ViewController).getPrimaryKeyComp(company: company)
//Call the function to reload the contIndex with only contacts for the company selected
contIndex = (delegate as!ViewController).getContactForCompany(ic: idcom)
cmbContact.reloadData()
}
}

UIButton subclass displays wrongly

I have a button that's created via a NIB file. I've derived a class from UIButton, replaced the class name in the NIB file.
Now my button displays with no background. The text is there, the text font and color are right, and it reacts to taps as expected, but it's as if the background is transparent. In the NIB, it's not transparent - I did not change any of the properties other than the class name.
The subclass is trivial - it overrides nothing (for now). Please, what am I doing wrong?
The reason I need a subclass of UIButton is because I want to be able, under certain circumstances, to drag text from the button to elsewhere. If there's an alternative way to handle drag and drop in a UIKit provided view, I'm willing to hear.
Check the states of the button in your NIB file.
It's possible that you are looking at the "active" state or something rather than the more common UICONTROLSTATENORMAL.
Honestly not sure what's wrong with the subclass, but the 'Net (including SO) is full of cautionary tales about subclassing UIButton, and how you shouldn't.
So I'll go with method swizzling on the four touch processing methods. The following function replaces the provided method of a button with my implementation (taken from the MyButton class), while saving the old one in the system button class under a different selector:
//Does NOT look at superclasses
static bool MethodInClass(Class c, SEL sel)
{
unsigned n,i ;
Method *m = class_copyMethodList(c, &n);
for(i=0;i<n;i++)
{
if(sel_isEqual(method_getName(m[i]), sel))
return true;
}
return false;
}
static void MountMethod(Class &buc, SEL SrcSel, SEL SaveSlotSel)
{
IMP OldImp = [buc instanceMethodForSelector:SrcSel];
IMP NewImp = [[MyButton class] instanceMethodForSelector:SrcSel];
if(OldImp && NewImp)
{
//Save the old implementation. Might conflict if the technique is used
//independently on many classes in the same hierarchy
Method SaveMe = class_getInstanceMethod(buc, SaveSlotSel);
if(SaveMe == NULL)
class_addMethod(buc, SaveSlotSel, OldImp, "v#:##");
else
method_setImplementation(SaveMe, OldImp);
//Note: the method's original implemenation might've been in the base class
if(MethodInClass(buc, SrcSel))
{
Method SrcMe = class_getInstanceMethod(buc, SrcSel);
if(SrcMe)
method_setImplementation(SrcMe, NewImp);
}
else //Add an override in the current class
class_addMethod(buc, SrcSel, NewImp, "v#:##");
}
}
And call it so:
Class buc = [bu class];
MountMethod(buc, #selector(touchesBegan:withEvent:), #selector(MyButton_SavedTouchesBegan:withEvent:));
MountMethod(buc, #selector(touchesCancelled:withEvent:), #selector(MyButton_SavedTouchesCancelled:withEvent:));
MountMethod(buc, #selector(touchesEnded:withEvent:), #selector(MyButton_SavedTouchesEnded:withEvent:));
MountMethod(buc, #selector(touchesMoved:withEvent:), #selector(MyButton_SavedTouchesMoved:withEvent:));
This has the disadvantage of mounting the said methods for all buttons, not just for the ones desired. In the MyButton's implementation, there's an additional check if the drag-drop functionality is to be enabled for this particular button. For that I've used associated objects.
One fine point is that touchesXXX methods are implemented in the UIControl class, not in the UIButton. So my first, naive implementation of swizzling would replace the method in UIControl instead of the button class. The current implementation does not assume either way. Also, it makes no assumptions about the run-time class of buttons. Could be UIButton, could be anything (and in real iOS, it's UIRoundedRectButton).

Custom iPad keyboard that looks like the system keyboards

I'm looking for a non-hackish solution for this, so basically -inputView. The part that I'm not sure about is how to make it look like the regular keyboards, from the background to the keys. I realize that I could photoshop an apple keyboard, but this seems like it is a little hackish, especially if apple (probably not but still possible) decides to change the look of their keyboards. I know Numbers has done an excellent job of making extra keyboards that look like the standard system ones, and I would like to do it like those (although obviously they have access to the same resources that made the system keyboards, including possible private frameworks, etc.)
I used the following:
tenDigitKeyboard.m
-(IBAction)pressedKey:(UIButton *)sender
{
[delegate pressedKey:sender.tag];
}
where delegate is defined as `id delegate;
then in the delegate i do...
-(void)pressedKey:(NSInteger)key
{
NSString * bufferString = model.string;
if (key == -1) {//delete
model.string = [bufferString substringWithRange:NSMakeRange(0, [bufferString length]-1)];
}else{
//will need to change the following to lookup key value based on a lookup of the button.tag
model.string = [bufferString stringByAppendingFormat:#"%i",key];
}
[self update];//updates the view
}
I got the keyboard button artwork from: http://www.teehanlax.com/blog/iphone-gui-psd-v4/
Create a view controller and xib. The xib should have 1-9,0 and delete buttons mapped to IBOutlets in your controller. Store and retain the return value string as a property. You can add decimals, etc. if you wish. In the header, store an edition block closure with a property (or alternatively create a delegate or use notification).
#property (copy) void(^valueChangedBlock)(NSString* string);
On touch up, each button sends an event to a method like this:
- (IBAction) pressKey:(id)sender
{
NSString *toAppend;
// Instead of this switch you can store the values in a dictionary mapped by sender.
switch(sender)
{
case oneButton: toAppend=#"1"; break;
case twoButton: toAppend=#"2"; break;
...
}
returnValue = [returnValue appendString:toAppend];
valueChanged(returnValue);
}
Obviously the delete key should remove a character from the end of the string instead of appending. Other than creating the controller and adding this view as the inputView, you should add the valueChangedBlock and set it to update the text field. You may want to put a clear custom button over the text field set to make the field first responder so it doesn't appear as if the user can edit at any point in the string.