NSCollectionView inside NSTableView (Binding with related entities) - macos

I have the following core data setup.
Data Setup
I have created an array controller called "SongsInMedleys" which is configured to contain the content of the SongsInMedleys with a specific medleyid.
I have created a view based Tableview which are bind to the SongsInMedleys array controller.
That is working fine, and I have managed to get the set the song title in a label by binding to Table Cell View and using objectValue.withSongs.title in the Model Key Path.
Now to my issue:
I would like to create a collection view inside the Table Cell View with all the verses to the related song. (objectValue.withSongs.withVerses)
Any suggestion to how I can do that???
Model of what I am trying to create :
Model

After some research I gave up try adding a collection view inside the tableview.
Insted I added my verses manually in the subclass of the NSTableCellView
-(void) setObjectValue:(id)objectValue {
if (objectValue != nil)
{
[super setObjectValue:objectValue];
SongsInMedleys *Sim = objectValue;
Songs *song = Sim.withSongs;
scrollView *scrollview = [[scrollView alloc] initWithFrame:NSMakeRect(10,5,[self frame].size.width-30,145)];
int addverses = 0;
for (VersesInSongs *verse in song.withVerses)
{
if ([verse.lyric length] > 0) {
addverses += 1;
}
}
NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(5, 10, ((addverses * (169+5))+5), 140)];
int x = 5;
NSSet *Verses = song.withVerses;
NSSortDescriptor *sortVerses = [[NSSortDescriptor alloc] initWithKey:#"number" ascending:YES];
NSArray *sortedVerses = [Verses sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortVerses]];
for (VersesInSongs *verse in sortedVerses)
{
if ([verse.lyric length] > 0) {
verseBox *box = [[verseBox alloc] initWithFrame:NSMakeRect(x, 10, 169, 130)];
[box setSong:song];
[box setVerse:verse];
[view addSubview:box];
x = x + 169+5;
}
}
[scrollview setDocumentView:view];
[self addSubview:scrollview];
}
}

Related

Disable autorotate for view in tabview controller

Hi how i can disable the autorotation for a view in a tabview controller??
i have testet to disable in a navigationclass, but thats not possible.
Thats my didFinishLaunching in the AppDelegate.m.
I hope everyone have an idea??
Thanks!
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Set the application defaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:#"YES"
forKey:#"myKeyName"];
[defaults registerDefaults:appDefaults];
[defaults synchronize];
[self setupFetchedResultsController];
if (![[self.fetchedResultsController fetchedObjects] count] > 0 ) {
NSLog(#"!!!!! ~~> There's nothing in the database so defaults will be inserted");
[self importCoreDataDefaultRoles];
[self importCoreDataDefaultMaterials];
[self importCoreDataDefaultPersons];
}
else {
NSLog(#"There's stuff in the database so skipping the import of default data");
}
// TAB BAR
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
// Override point for customization after application launch.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
NSLog(#"I'm an iPad");
// *** Set up the Persons Split Views (2-Way Delegation & Pass Managed Object Context) *** //
// Set up SPLIT VIEW for Persons
UISplitViewController *splitViewController = [[tabBarController viewControllers] objectAtIndex:0];
// Set up Split View MASTER view for Persons
UINavigationController *personsMasterTVCnav = [splitViewController.viewControllers objectAtIndex:0];
splitViewController.delegate = (id)personsMasterTVCnav.topViewController;
PersonsTVC *personsTVC = [[personsMasterTVCnav viewControllers] objectAtIndex:0];
personsTVC.managedObjectContext = self.managedObjectContext;
// Set up Split View DETAIL view for Persons
UINavigationController *personsDetailTVCnav = [splitViewController.viewControllers objectAtIndex:1];
PersonDetailTVC *personDetailTVC = [personsDetailTVCnav.viewControllers objectAtIndex:0];
// Set up MASTER and DETAIL delegation so we can send messages between views
personsTVC.delegate = personDetailTVC;
personDetailTVC.delegate = personsTVC;
// *** Set up the Roles Views *** (Pass Managed Object Context)//
UINavigationController *rolesTVCnav = [[tabBarController viewControllers] objectAtIndex:1];
RolesTVC *rolesTVC = [[rolesTVCnav viewControllers] objectAtIndex:0];
rolesTVC.managedObjectContext = self.managedObjectContext;
// *** Set up the Materials Views *** (Pass Managed Object Context)//
UINavigationController *materialsTVCnav = [[tabBarController viewControllers] objectAtIndex:2];
MaterialsTVC *materialsTVC = [[materialsTVCnav viewControllers] objectAtIndex:0];
materialsTVC.managedObjectContext = self.managedObjectContext;
// Set delegate for splitViewController
splitViewController.delegate = personDetailTVC;
}
else
{
NSLog(#"I'm an iPhone or iPod Touch");
// The Two Navigation Controllers attached to the Tab Bar (At Tab Bar Indexes 0 and 1)
UINavigationController *personsTVCnav = [[tabBarController viewControllers] objectAtIndex:0];
UINavigationController *rolesTVCnav = [[tabBarController viewControllers] objectAtIndex:1];
UINavigationController *materialsTVCnav = [[tabBarController viewControllers] objectAtIndex:2];
// The Persons Table View Controller (First Nav Controller Index 0)
PersonsTVC *personsTVC = [[personsTVCnav viewControllers] objectAtIndex:0];
personsTVC.managedObjectContext = self.managedObjectContext;
// The Roles Table View Controller (Second Nav Controller Index 0)
RolesTVC *rolesTVC = [[rolesTVCnav viewControllers] objectAtIndex:0];
rolesTVC.managedObjectContext = self.managedObjectContext;
// The Materials Table View Controller (Third Nav Controller Index 0)
MaterialsTVC *materialsTVC = [[materialsTVCnav viewControllers] objectAtIndex:0];
materialsTVC.managedObjectContext = self.managedObjectContext;
}
return YES;
}
Disabling entire UIViewController auto-rotation
A UIViewController embedded in a UITabBarController is relying upon that last controller to handle the -supportedInterfaceOrientations messages. It is not ; basically the same problem as in this post: iOS 6 rotations: supportedInterfaceOrientations doesn´t work?
You must subclass your UITabBarController, and add this code to query each tab:
// In UITabBarController subclass
- (BOOL)shouldAutorotate;
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
UIViewController * top;
UIViewController * tab = self.selectedViewController;
if([tab isKindOfClass:
([UINavigationController class])]) {
top = [((UINavigationController *)tab)
topViewController];
}
if ([top respondsToSelector:#selector(supportedInterfaceOrientations)])
return [top supportedInterfaceOrientations];
else
return [super supportedInterfaceOrientations];
}
Of course, you must still respect the general auto-rotation rules and set the flags in the plist.
For each UIViewController subclass you want to prevent orientation changes, respond to supportedInterfaceOrientations as so:
// In UIViewController subclass
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
// Or whatever orientation you support
}
See this post for further details: Handling autorotation for one view controller in iOS7
Rotating a UIViewController except one or more subviews
Use this method:
-(void)counterRotateView:(UIView *)view
toInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration
{
NSParameterAssert(view);
CALayer* layer = view.layer;
CABasicAnimation* animation;
animation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
CGFloat tau = 0;
switch (toInterfaceOrientation) {
case UIInterfaceOrientationLandscapeLeft:
tau = 0.5; break;
case UIInterfaceOrientationLandscapeRight:
tau = -0.5; break;
case UIInterfaceOrientationPortraitUpsideDown:
tau = 1; break;
case UIInterfaceOrientationPortrait:
default:
break;
}
animation.toValue = [NSNumber numberWithFloat:tau * M_PI];
animation.duration = duration;
animation.cumulative = YES;
animation.repeatCount = 1;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
[layer addAnimation:animation forKey:#"transform.rotation.z"];
}
And invoke it from here:
-(void) willRotateToInterfaceOrientation:
(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration
{
[self counterRotateView:someView
toInterfaceOrientation:toInterfaceOrientation
duration:duration];
}

Nested NSCollection View

I am trying to create a nested collection view. First I did for one level.
Created a data model class with String header. In app delegate created an array sectionTitle. Now in the nib, I added collection view & array controller and did all the bindings following this guide. Next in awakeFromNib I populated some random data
- (void)awakeFromNib {
int idx = 0;
NSMutableArray *sectionTitle = [[NSMutableArray alloc] init];
while (idx < 1) {
HeaderModel *header = [[HeaderModel alloc] init];
[header setHeader:[NSString stringWithFormat:#"Section %d", idx]];
[sectionTitle addObject:header];
idx++;
}
[self setHeaderData:sectionTitle];
}
Running it will give me 4 sections. I want to achieve similar layout as this. Section title, under it another collection of items. The answer given there only hints at using Nested collection view.
So I added another collection view in the first view prototype. Then I followed the same approach what I did for the first view(with different data model and array).
- (void)awakeFromNib {
int idx = 0;
NSMutableArray *sectionTitle = [[NSMutableArray alloc] init];
NSMutableArray *groupData = [[NSMutableArray alloc] init];
while (idx < 1) {
HeaderModel *header = [[HeaderModel alloc] init];
DataModel *name = [[DataModel alloc] init];
[header setHeader:[NSString stringWithFormat:#"Section %d", idx]];
[name setName:[NSString stringWithFormat:#"Name %d", idx]];
[sectionTitle addObject:header];
[groupData addObject:name];
idx++;
}
[self setHeaderData:sectionTitle];
[self setData:groupData]; //NSCollectionView item prototype must not be nil.
}
But now I get the error NSCollectionView item prototype must not be nil.
How do I resolve this ?
I have just answered a similar question here
But somehow by inserting the second NSCollectionView with I.B, you get a corrupted prototype for your inner NSCollectionViewItem. Simply try to extract each associated NSView into its own .xib

How To Provide Search-As-You-Type Filtering With UICollectionView?

I have a UICollectionView added to a ViewController. The UICollectionView displays a grid of items with peoples names on each cell.
I would like to add search as you type functionality that will filter the UICollectionView as the user types in their name to a searchbar or UITextField on the ViewController so that it doesn't scroll with the content in the UICollectionView.
Even though a few places I have read that UICollectionView is similar to UITableView I don't see that implementing this filter/search functionality is the same in UICollectionView as it is with UITableView and need some help with it.
Does anyone have a good example of doing this search/filter as you type functionality with UICollectionView?
I solved it by doing the following (hope it helps somebody else):
I populate my UICollectionView from CoreData into an NSArray:
self.allCVData = [context executeFetchRequest:fetchRequest error:&error];
then add my NSArray to an NSMutableArray so that I can use that for filtering on the UICollection:
self.filteredCVData = [[NSMutableArray alloc] initWithArray:allCVData];
Added a UITextField and called it searchField.
Added a selector in viewDidLoad:
[mytextfield addTarget:self action:#selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
Added a method to accept changes in the UITextField:
-(void) textDidChange:(id)sender
{
UITextField* searchField = (UITextField *) sender;
if(searchField.text.length == 0)
{
self.isFiltered = FALSE;
[self.filteredCVData removeAllObjects];
[self.filteredCVData addObjectsFromArray:self.allCVData];
}
else
{
self.isFiltered = true;
[self.filteredCVData removeAllObjects];
self.filteredCVData = [[NSMutableArray alloc] init];
LogInfo(#"Before Looping in allCVData Array.");
for (OLPerson* person in allCVData)
{
NSRange firstnameRange = [person.firstname rangeOfString:searchField.text options:NSCaseInsensitiveSearch];
NSRange surnameRange = [person.surname rangeOfString:searchField.text options:NSCaseInsensitiveSearch];
if(firstnameRange.location != NSNotFound || surnameRange.location != NSNotFound)
{
[self.filteredCVData addObject:person];
}
}
}
[self.collectionView reloadData];
}

UIBarButtonItem frame? [duplicate]

UIBarButtonItem does not extend UIView, so there is nothing like a frame property.
But is there any way I can get what is it's CGRect frame, relative to the application UIWindow?
Do you like to use private APIs? If yes,
UIView* view = thatItem.view;
return [view convertRect:view.bounds toView:nil];
Of course no one wants this when targeting the AppStore. A more unreliable method, and also uses undocumented features, but will pass Apple's test, is to loop through the subviews to look for the corresponding button item.
NSMutableArray* buttons = [[NSMutableArray alloc] init];
for (UIControl* btn in theToolbarOrNavbar.subviews)
if ([btn isKindOfClass:[UIControl class]])
[buttons addObject:btn];
UIView* view = [buttons objectAtIndex:index];
[buttons release];
return [view convertRect:view.bounds toView:nil];
The index is the index to your bar item in the array of .items, after removing all blank items. This assumes the buttons are arranged in increasing order, which may not be. A more reliable method is to sort the buttons array in increasing .origin.x value. Of course this still assumes the bar button item must inherit the UIControl class, and are direct subviews of the toolbar/nav-bar, which again may not be.
As you can see, there are a lot of uncertainty when dealing with undocumented features. However, you just want to pop up something under the finger right? The UIBarButtonItem's .action can be a selector of the form:
-(void)buttonClicked:(UIBarButtonItem*)sender event:(UIEvent*)event;
note the event argument — you can obtain the position of touch with
[[event.allTouches anyObject] locationInView:theWindow]
or the button view with
[[event.allTouches anyObject] view]
Therefore, there's no need to iterate the subviews or use undocumented features for what you want to do.
I didn't see this option posted (which in my opinion is much simpler), so here it is:
UIView *barButtonView = [barButtonItem valueForKey:#"view"];
In iOS 3.2, there's a much easier way to show an Action Sheet popover from a toolbar button. Merely do something like this:
- (IBAction)buttonClicked:(UIBarButtonItem *)sender event:(UIEvent *)event
{
UIActionSheet *popupSheet;
// Prepare your action sheet
[popupSheet showFromBarButtonItem:sender animated:YES];
}
This is the implementation I use for my WEPopover project: (https://github.com/werner77/WEPopover):
#implementation UIBarButtonItem(WEPopover)
- (CGRect)frameInView:(UIView *)v {
UIView *theView = self.customView;
if (!theView.superview && [self respondsToSelector:#selector(view)]) {
theView = [self performSelector:#selector(view)];
}
UIView *parentView = theView.superview;
NSArray *subviews = parentView.subviews;
NSUInteger indexOfView = [subviews indexOfObject:theView];
NSUInteger subviewCount = subviews.count;
if (subviewCount > 0 && indexOfView != NSNotFound) {
UIView *button = [parentView.subviews objectAtIndex:indexOfView];
return [button convertRect:button.bounds toView:v];
} else {
return CGRectZero;
}
}
#end
As long as UIBarButtonItem (and UITabBarItem) does not inherit from UIView—for historical reasons UIBarItem inherits from NSObject—this craziness continues (as of this writing, iOS 8.2 and counting ... )
The best answer in this thread is obviously #KennyTM's. Don't be silly and use the private API to find the view.
Here's a oneline Swift solution to get an origin.x sorted array (like Kenny's answer suggests):
let buttonFrames = myToolbar.subviews.filter({
$0 is UIControl
}).sorted({
$0.frame.origin.x < $1.frame.origin.x
}).map({
$0.convertRect($0.bounds, toView:nil)
})
The array is now origin.x sorted with the UIBarButtonItem frames.
(If you feel the need to read more about other people's struggles with UIBarButtonItem, I recommend Ash Furrow's blog post from 2012: Exploring UIBarButtonItem)
I was able to get Werner Altewischer's WEpopover to work by passing up the toolbar along with the
UIBarButton:
Mod is in WEPopoverController.m
- (void)presentPopoverFromBarButtonItem:(UIBarButtonItem *)item toolBar:(UIToolbar *)toolBar
permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections
animated:(BOOL)animated
{
self.currentUIControl = nil;
self.currentView = nil;
self.currentBarButtonItem = item;
self.currentArrowDirections = arrowDirections;
self.currentToolBar = toolBar;
UIView *v = [self keyView];
UIButton *button = nil;
for (UIView *subview in toolBar.subviews)
{
if ([[subview class].description isEqualToString:#"UIToolbarButton"])
{
for (id target in [(UIButton *)subview allTargets])
{
if (target == item)
{
button = (UIButton *)subview;
break;
}
}
if (button != nil) break;
}
}
CGRect rect = [button.superview convertRect:button.frame toView:v];
[self presentPopoverFromRect:rect inView:v permittedArrowDirections:arrowDirections animated:animated];
}
-(CGRect) getBarItemRc :(UIBarButtonItem *)item{
UIView *view = [item valueForKey:#"view"];
return [view frame];
}
You can get it from the UINavigationBar view. The navigationBar is a UIView which has 2 or 3 custom subviews for the parts on the bar.
If you know that the UIBarButtonItem is currently shown in the navbar on the right, you can get its frame from navbar's subviews array.
First you need the navigationBar which you can get from the navigationController which you can get from the UIViewController. Then find the right most subview:
UINavigationBar* navbar = curViewController.navigationController.navigationBar;
UIView* rightView = nil;
for (UIView* v in navbar.subviews) {
if (rightView==nil) {
rightView = v;
} else if (v.frame.origin.x > rightView.frame.origin.x) {
rightView = v; // this view is further right
}
}
// at this point rightView contains the right most subview of the navbar
I haven't compiled this code so YMMV.
This is not the best solution and from some point of view it's not right solution and we can't do like follow because we access to object inside UIBarBattonItem implicitly, but you can try to do something like:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
[button setImage:[UIImage imageNamed:#"Menu_Icon"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(didPressitem) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.rightBarButtonItem = item;
CGPoint point = [self.view convertPoint:button.center fromView:(UIView *)self.navigationItem.rightBarButtonItem];
//this is like view because we use UIButton like "base" obj for
//UIBarButtonItem, but u should note that UIBarButtonItem base class
//is NSObject class not UIView class, for hiding warning we implicity
//cast UIBarButtonItem created with UIButton to UIView
NSLog(#"point %#", NSStringFromCGPoint(point));
as result i got next:
point {289, 22}
Before implement this code, be sure to call [window makeKeyAndVisible] in your Applition delegate application:didFinishLaunchingWithOptions: method!
- (void) someMethod
{
CGRect rect = [barButtonItem convertRect:barButtonItem.customview.bounds toView:[self keyView]];
}
- (UIView *)keyView {
UIWindow *w = [[UIApplication sharedApplication] keyWindow];
if (w.subviews.count > 0) {
return [w.subviews objectAtIndex:0];
} else {
return w;
}
}
I handled it as follows:
- (IBAction)buttonClicked:(UIBarButtonItem *)sender event:(UIEvent *)event
{
UIView* view = [sender valueForKey:#"view"]; //use KVO to return the view
CGRect rect = [view convertRect:view.bounds toView:self.view];
//do stuff with the rect
}

NSRuleEditor: Criteria for new row

When I hit the "+" button on a row in NSRuleEditor, a new row is created. How can I take influence on the criteria used for that row.
It seems NSRuleEditor defaults to selecting the first criterion sequentially from the list of possible values. I would much rather have the new row match the row where the "+" was clicked.
I was able to fake it by subclassing a private method:
- (void)_addOptionFromSlice:(id)slice ofRowType:(unsigned int)type
{
int rowIndex = [(NSRuleEditorViewSlice*)slice rowIndex];
NSArray *criteriaForRow = [self criteriaForRow:rowIndex];
NSArray *displayValuesForRow = [self displayValuesForRow:rowIndex];
self.template = [NSArray arrayWithObjects:criteriaForRow, displayValuesForRow, nil];
[super _addOptionFromSlice:slice ofRowType:type];
}
- (void)insertRowAtIndex:(NSInteger)rowIndex withType:(NSRuleEditorRowType)rowType asSubrowOfRow:(NSInteger)parentRow animate:(BOOL)shouldAnimate
{
[super insertRowAtIndex:rowIndex withType:rowType asSubrowOfRow:parentRow animate:shouldAnimate];
NSArray *template = self.template;
if (template != nil) {
[self setCriteria:[template objectAtIndex:0] andDisplayValues:[template objectAtIndex:1] forRowAtIndex:rowIndex];
}
}

Resources