How do you change the width of a UITableView? - objective-c

I'm new to iPhone development, coming from a web application development background and I'm working on my first project. I chose to create a Navigation based project, since after reading it seemed to be the easiest way to get what I'm after. How do you change the width of the UITableView? Eventually, I'd like to have a top bar, UITableView, and bottom bar be 304px wide. I've tried the following in my RootViewController's viewDidLoad method, but I'm doing it wrong:
CGRect tableViewFrame = self.tableView.frame;
tableViewFrame.size.width = 200;
self.tableView.frame = tableViewFrame;
Thanks for any help in advance.

If you want to change the width of the tableViewCell.. go to cellForRowAtIndexPath, and assign it there.
You could also do -
CGFloat tableBorderLeft = 1;
CGFloat tableBorderRight = 1;
CGRect tableRect = self.view.frame;
tableRect.origin.x += tableBorderLeft; // make the table begin a few pixels right from its origin
tableRect.size.width -= tableBorderLeft + tableBorderRight; // reduce the width of the table
tableView.frame = tableRect;
For changing the size of header
-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
return 150.0; //Give a value
}
For changing size of footer
-(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section
{
return 150.0;//Give a value
}

Related

NSTableCellView padding

How can I add padding to a NSTableCellView?
I want the contents to have a padding of 10px, similar to how you would do it in plain HTML. (All sides). The text should be vertically centered in the middle.
At the moment I'm doing this in a subclass of NSTextFieldCell. But this doesn't seem to work correctly.
When I edit the text, the edit text field does not use the padding from the textfieldcell.
Image 2:
Here is the code I currently have, (subclass of NSTextFieldCell)
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
NSRect titleRect = [self titleRectForBounds:cellFrame];
NSAttributedString *aTitle = [self attributedStringValue];
if ([aTitle length] > 0) {
[aTitle drawInRect:titleRect];
}
}
- (NSRect)titleRectForBounds:(NSRect)bounds
{
NSRect titleRect = bounds;
titleRect.origin.x += 10;
titleRect.origin.y = 2;
NSAttributedString *title = [self attributedStringValue];
if (title) {
titleRect.size = [title size];
} else {
titleRect.size = NSZeroSize;
}
// We don't want the width of the string going outside the cell's bounds
CGFloat maxX = NSMaxX(bounds);
CGFloat maxWidth = maxX - NSMinX(titleRect);
if (maxWidth < 0) {
maxWidth = 0;
}
titleRect.size.width = MIN(NSWidth(titleRect), maxWidth);
return titleRect;
}
Below are some options for getting the padding.
Earlier I had some problems getting the correct bounding box height for NSAttributedString. I don't remember how I solved them but there are some discussions on the matter.
Idea #1:
Use NSTableView's intercell spacing. It's also available in the Interface Builder from the table view's size tab. Look for cell spacing.
Idea #2:
When editing the interface:
Unless you need something else, use the text or image and text table cell view provided by Apple.
Change the height of the table cell view inside the table view using the size tab.
Reposition the text field inside the table cell view.
Idea #3:
Use a custom cell.
You can change the field editor position by overriding -[NSTextFieldCell editWithFrame:inView:editor:delegate:event:]. There's also -[NSTextFieldCell setUpFieldEditorAttributes]. I found this sample code useful.
If you increase the height of the cell, there are a couple of ways to make NSTextFieldCell draw the text vertically centered.
use the setContentInset method.it sets the distance of the inset between the content view and the enclosing table view.
for example
self.tableView.contentInset = UIEdgeInsetsMake(-35, 0, -20, 0);

Automatically adjust height of a NSTableView

I have asked this question once before, but I'm just not very satisfied with the solution.
Automatically adjust size of NSTableView
I want to display a NSTableView in a NSPopover, or in a NSWindow.
Now, the window's size should adjust with the table view.
Just like Xcode does it:
This is fairly simple with Auto Layout, you can just pin the inner view to the super view.
My problem is, that I can't figure out the optimal height of the table view.
The following code enumerates all available rows, but it doesn't return the correct value, because the table view has other elements like separators, and the table head.
- (CGFloat)heightOfAllRows:(NSTableView *)tableView {
CGFloat __block height;
[tableView enumerateAvailableRowViewsUsingBlock:^(NSTableRowView *rowView, NSInteger row) {
// tried it with this one
height += rowView.frame.size.height;
// and this one
// height += [self tableView:nil heightOfRow:row];
}];
return height;
}
1. Question
How can I fix this? How can I correctly calculate the required height of the table view.
2. Question
Where should I run this code?
I don't want to implement this in a controller, because it's definitely something that the table view should handle itself.
And I didn't even find any helpful delegate methods.
So I figured best would be if you could subclass NSTableView.
So my question 2, where to implement it?
Motivation
Definitely worth a bounty
This answer is for Swift 4, targeting macOS 10.10 and later:
1. Answer
You can use the table view's fittingSize to calculate the size of your popover.
tableView.needsLayout = true
tableView.layoutSubtreeIfNeeded()
let height = tableView.fittingSize.height
2. Answer
I understand your desire to move that code out of the view controller but since the table view itself knows nothing about the number of items (only through delegation) or model changes, I would put that in the view controller. Since macOS 10.10, you can use preferredContentSize on your NSViewController inside a popover to set the size.
func updatePreferredContentSize() {
tableView.needsLayout = true
tableView.layoutSubtreeIfNeeded()
let height = tableView.fittingSize.height
let width: CGFloat = 320
preferredContentSize = CGSize(width: width, height: height)
}
In my example, I'm using a fixed width but you could also use the calculated one (haven't tested it yet).
You would want to call the update method whenever your data source changes and/or when you're about to display the popover.
I hope this solves your problem!
You can query the frame of the last row to get the table view's height:
- (CGFloat)heightOfTableView:(NSTableView *)tableView
{
NSInteger rows = [self numberOfRowsInTableView:tableView];
if ( rows == 0 ) {
return 0;
} else {
return NSMaxY( [tableView rectOfRow:rows - 1] );
}
}
This assumes an enclosing scroll view with no borders!
You can query the tableView.enclosingScrollView.borderType to check whether the scroll view is bordered or not. If it is, the border width needs to be added to the result (two times; bottom and top). Unfortunately, I don't know of the top of my head how to get the border width.
The advantage of querying rectOfRow: is that it works in the same runloop iteration as a [tableView reloadData];. In my experience, querying the table view's frame does not work reliably when you do a reloadData first (you'll get the previous height).
Interface Builder in Xcode automatically puts the NSTableView in an NSScrollView. The NSScrollView is where the headers are actually located. Create a NSScrollView as your base view in the window and add the NSTableView to it:
NSScrollView * scrollView = [[NSScrollView alloc]init];
[scrollView setHasVerticalScroller:YES];
[scrollView setHasHorizontalScroller:YES];
[scrollView setAutohidesScrollers:YES];
[scrollView setBorderType:NSBezelBorder];
[scrollView setTranslatesAutoresizingMaskIntoConstraints:NO];
NSTableView * table = [[NSTableView alloc] init];
[table setDataSource:self];
[table setColumnAutoresizingStyle:NSTableViewUniformColumnAutoresizingStyle];
[scrollView setDocumentView:table];
//SetWindow's main view to scrollView
Now you can interrogate the scrollView's contentView to find the size of the NSScrollView size
NSRect rectOfFullTable = [[scrollView contentView] documentRect];
Because the NSTableView is inside an NSScrollView, the NSTableView will have a headerView which you can use to find the size of your headers.
You could subclass NSScrollView to update it's superview when the table size changes (headers + rows) by overriding the reflectScrolledClipView: method
I'm not sure if my solution is any better than what you have, but thought I'd offer it anyway. I use this with a print view. I'm not using Auto Layout. It only works with bindings – would need adjustment to work with a data source.
You'll see there's an awful hack to make it work: I just add 0.5 to the value I carefully calculate.
This takes the spacing into account but not the headers, which I don't display. If you are displaying the headers you can add that in the -tableView:heightOfRow: method.
In NSTableView subclass or category:
- (void) sizeHeightToFit {
CGFloat height = 0.f;
if ([self.delegate respondsToSelector:#selector(tableView:heightOfRow:)]) {
for (NSInteger i = 0; i < self.numberOfRows; ++i)
height = height +
[self.delegate tableView:self heightOfRow:i] +
self.intercellSpacing.height;
} else {
height = (self.rowHeight + self.intercellSpacing.height) *
self.numberOfRows;
}
NSSize frameSize = self.frame.size;
frameSize.height = height;
[self setFrameSize:frameSize];
}
In table view delegate:
// Invoke bindings to get the cell contents
// FIXME If no bindings, use the datasource
- (NSString *) stringValueForRow:(NSInteger) row column:(NSTableColumn *) column {
NSDictionary *bindingInfo = [column infoForBinding:NSValueBinding];
id object = [bindingInfo objectForKey:NSObservedObjectKey];
NSString *keyPath = [bindingInfo objectForKey:NSObservedKeyPathKey];
id value = [[object valueForKeyPath:keyPath] objectAtIndex:row];
if ([value isKindOfClass:[NSString class]])
return value;
else
return #"";
}
- (CGFloat) tableView:(NSTableView *) tableView heightOfRow:(NSInteger) row {
CGFloat result = tableView.rowHeight;
for (NSTableColumn *column in tableView.tableColumns) {
NSTextFieldCell *dataCell = column.dataCell;
if (![dataCell isKindOfClass:[NSTextFieldCell class]]) continue;
// Borrow the prototype cell, and set its text
[dataCell setObjectValue:[self stringValueForRow:row column:column]];
// Ask it the bounds for a rectangle as wide as the column
NSRect cellBounds = NSZeroRect;
cellBounds.size.width = [column width]; cellBounds.size.height = FLT_MAX;
NSSize cellSize = [dataCell cellSizeForBounds:cellBounds];
// This is a HACK to make this work.
// Otherwise the rows are inexplicably too short.
cellSize.height = cellSize.height + 0.5;
if (cellSize.height > result)
result = cellSize.height;
}
return result;
}
Just get -[NSTableView frame]
NSTableView is embed in NSScrollView, but has the full size.

How to center a grouped table view both vertically and horizontally on iOS?

I've been looking for a way to center a table view both vertically and horizontally but I can't seem to figure out if this is better done / possible using interface builder alone. If not what method should I override to set this in objective-c itself?
Also will this use the vertical screen size of the device so it actually centers the grouped table view on both legacy iPhone devices and the new iPhone 5?
Thank you in advance
This is what I use to get the proper centered frame. Note that the view needs to have proper springs and struts so it resizes when phone calls come in, etc:
+ (CGRect)centeredFrameForSize:(CGSize)size inRect:(CGRect)rect
{
CGRect frame;
frame.origin.x = rintf((rect.size.width - size.width)/2) + rect.origin.x;
frame.origin.y = rintf((rect.size.height - size.height)/2) + rect.origin.y;
// if(frame.origin.x < 0) frame.origin.x = 0;
// if(frame.origin.y < 0) frame.origin.y = 0;
frame.size = size;
return frame;
}

UIScrollView moves image to the top left corner when zooming in

Looking at this question: Prevent UIScrollView from moving contents to top-left, i'm having the exact issue.
I'm using this tutorial: http://cocoadevblog.heroku.com/iphone-tutorial-uiimage-with-zooming-tapping-rotation
Back to the similar question, if i disable the UIScrollViewPanGestureRecognizer, i'm not able to pan the zoomed image anymore.
I have a UIImageView within a UIScrollView, and i want to be able to zoom and pan the image as well.
How can i do tho disable the contents moving to the top left corner when zooming in?
Seems i solved tweaking my UiScrollView Autosizing and Origin in the Size inspector \ Attributes inspector. I unchecked Paging Enabled and the magic happened.
Just in case anyone else comes here and none of the other answers seem to work ( which was my case ), what did the trick for me was setting the contentSize of the scrollView. Just set it to the size whatever subview you are zooming in on and it should work.
Make a subclass of UIScrollView, and add this method to it:
- (void)layoutSubviews {
[super layoutSubviews];
// center the image as it becomes smaller than the size of the screen
CGSize boundsSize = self.bounds.size;
//get the subView that is being zoomed
UIView *subView = [self.delegate viewForZoomingInScrollView:self];
if(subView)
{
CGRect frameToCenter = subView.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
frameToCenter.origin.x = 0;
// center vertically
if (frameToCenter.size.height < boundsSize.height)
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
frameToCenter.origin.y = 0;
subView.frame = frameToCenter;
}
else
NSLog(#"No subView set for zooming in delegate");
}
If I understand you right, you want to allowing scrolling only when theImageView is zoomed in, then a scrollView.zoomScale > 1. For my app requirement I am using this.
Add UIScrollView's delegate method as follows and check.
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView
{
CGFloat offsetY = 0;
if (aScrollView.zoomScale > 1)
offsetY = aScrollView.contentOffset.y;
[aScrollView setContentOffset: CGPointMake(aScrollView.contentOffset.x, offsetY)];
}

Scrolling view like app details screen

I am trying to figure out the best way to create a view like the app details screen in the AppStore app. I want a thumbnail and text content under it that all scrolls if the content is too long. Is this done in a tableview or a scrollview?
I've made one in a scrollview. I calculated the size of each element's frame from this method:
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
I kept a running total of the y size by adding it on after each label. At the end, if the scroll view was over a certain size (the length of my page) I gave that size to the scroll view, adding a little on the end so it wouldn't bump against the bottom.
Here's some code:
int currentYPos;
CGSize maximumSize = CGSizeMake(300, 9999);
[scrollView setCanCancelContentTouches:NO];
scrollView.indicatorStyle = UIScrollViewIndicatorStyleDefault;
scrollView.clipsToBounds = YES;
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = NO;
// set the title frame size
self.titleLabel.text = self.title;
CGSize titleSize = [self.titleLabel.text sizeWithFont:self.titleLabel.font
constrainedToSize:maximumSize
lineBreakMode:self.titleLabel.lineBreakMode];
currentYPos = titleSize.height + 20;
CGRect titleFrame = CGRectMake(10, 0, 300, currentYPos);
self.titleLabel.frame = titleFrame;
Note that many of the titleLabel properties were set on a label in IB.