UITableView with text that is both right-aligned and indented - iphone

I wanted to make a UITableView with text that is both right-aligned and indented as depicted in the image below:
Unfortunately, I can not do this by writing :-
cell.textLabel.textAlignment = UITextAlignmentRight;
cell.indentationLevel = 10; // or even -10
Can this be done using UITableView's properties? If not, the only way I could think of is using [myString drawInRect:withFont:]; but I would like to go through methods based on alignment and indentation before getting into that [I have already written code for that :-) ], so other work-arounds are welcome!
Additional info: The indentation varies with accelerometer values so I can not have hard-coded Label frame positions. I've uploaded sample code at github in which I've used only the alignment and indentation info so far, so continuing to use that would make this easier.

Subclass UITableViewCell and you can position the frame of the text label however you like. In the if statement where you dequeueReusableCellWithIdentifier: where a reusable cell doesn't exist, just modify the frame and then set the label to use the adjusted frame with setFrame. The autoresizing mask should remain the same.

You could always create your own custom cells and place a UITextLabel in the cell, and make the UITextLabel's alignment right aligned.
Also set the autoresizing mask of the UITextLabel to the right so the indentation distance stays the same no matter the orientation.

Related

UILabel not wrapping correctly after text change

I'm working via the IB and have a UILabel that's stretched almost to the end of the layout. I have it set with Lines=2, because the max amount of lines it should take is 2. However if it's only 1 line long, I would like it to have a vertical justification of top.
Label settings in IB:
Lines:2
Line breaks: Word wrap
In code, in the viewDidLoad method I set the text of the UILabel. However as part of the functionality at a point the text must change. This is my code:
[_main_lbl1 setText:[myUI MAIN_TITLE]]; //Always only 1 line
[_main_lblsub1 setText:[myUI SUB_TITLE]]; //May be 1 or 2 lines
[_main_lblsub1 sizeToFit]; //Causes vertical alignment (I believe)
Whenever I change the text and rerun sizeToFit, the text wrapping becomes totally messed up. Instead of reaching almost the end of the UILabel as set up in the IB, in some cases the text will wrap at little more than half the distance, in some cases it doesn't wrap at all.
Image of layout in IB:
Image of resulting label in simulator:
In the first label it seems to be working ok, the second label doesn't wrap at all.
Is there anything I have to do to keep the text wrapping when changing the UILabel text? Anything else I'm missing?
Note: Updated question to include more detail and pics.
Thanks
The issue is that you're using sizeToFit. Which stretches the label out to fit the text. If you need to change the size you can use:
CGSize maxSize = CGSizeMake(320, 9999); // 999 means it can be as tall as you like
CGSize textSize = [label.text sizeWithFont:label.font
constrainedToSize:maxSize];
label.size = textSize;
You shouldn't have to do anything special. It will automatically wrap the text to fit when you change it. Otherwise the text would run out of the text labels bounds (which is not what you want). Your problem is that sizeToFit permanently changes the frame of the label. It makes it as small as possible while still showing the text. You are having it resize its frame to the original text and then you are changing the text so it is no longer sized properly. You should reset the frame back to it's original, change the text, and finally call size to fit again.
In viewDidLoad:
self.originalFrame = self.mainLabelSub1.frame;
Then in viewWillAppear:
self.mainLabel1.frame = self.originalFrame;
self.mainLabel1.text = #"New Text";
Note:
A good way to see the borders of the text label to get an idea for the wrapping potential is to temporary set the background of the label to something like magentaColor that stands out.

iphone code for auto uiLabel & uiTableViewCell resizing when font changed?

Can someone summarise the key pieces of objective-c code that would assist in solving this.
Objective - Autoresize a UITableView after a user changes the font size. Therefore if the user increases or descreases font both the (a) uiLabel heights should change to ensure they nicely include text, and (b) uiTableViewCell heights should also adjust.
Assumption is that:
UITableView has been extended via
creation of a custom cell view -
i.e. create a new view in a NIB that
forms for the content view of the
UITableView cells
each custom
cell has four UILabel's which form a
2 x 2 patter of UILabels - i.e. two
on top line and two on bottom line
so as the user increases the font
the horizontal spacing of the
UILabels would remain the same,
however the label heights would
change
So I assume the challenge / questions I have would include (and hopefully be answered by some sample code that someone can post)
Is it OK that the starting point here is an already laid out custom UITableViewCell in InterfaceBuilder? (or does the solution require it is constructed totally programmatically)?
How to calculate the heights the label's should be? Is this just with the NSString method "sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:", and do I need to add addition for margins etc?
How programmatically to increase the height of the labels dynamically - in which method do you do this & how to change the height itself
How to ensure that when UILabel at the top is expanded & grows, that it automatically pushes down the UILabel on the 2nd row? Does this happen by default or is there a specific property/setting you have to you to ensure this hapens.
How to then automatically increase the height of the TableViewcell, after the above has occurred. Which method to do this in, and how programmatically to perform the increase & redraw.
Hope this makes sense.
thanks
You can base on the XIB file as a default layout, then adjust the position/size later during runtime.
Yes use that method to calculate the required height. You need to add margins between labels yourself.
Change the label's frame.
You need to calculate the x,y of the 2nd row's label base on the x,y,height from the 1st row's label + margin.
hook with the following method and return the new height:
(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
To get the UILabel's height to match your target font, you use the sizeWithFont function of NSString.
NSString *myText = #"Go Hokies";
UIFont *myFont = [UIFont boldSystemFontOfSize:15];
CGFloat lineHeight = [myText sizeWithFont:myFont].height;
The problem you may run into is if the text doesn't fit horizontally in the bounds you've defined. If you want the font to downsize accordingly, turn on the adjustment flag and set a min like this.
myUILabel.minimumFontSize = 10;
myUILabel.adjustsFontSizeToFitWidth = YES;

UITableView Did Load (Done drawing the cells)

Question
How can you detect when the Table View is done drawing the cells?
Issue
I got two labels within the contentView of an UITableViewCell. The size of these labels are dynamic. I was able to do so by subclassing UITableViewCell, in the drawRect method I adjust the frames of the two labels depending on their content. Now I want to align all the second labels.
My Thoughts in Steps
Determine the content in the table view and let it load automatically.
Run through the table view cells and determine the x position of the second label within the UITableViewCell that is the furtherest away.
Store this x position and when any cell is drawn use this x position to place the second label.
The problem is that if I use the following code:
for (int row = 0; row < [self.tableView numberOfRowsInSection:section]; row++) {
UITableViewCustomCell *cell = (UITableViewCustomCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
NSLog ([cell.labelTwo description]);
}
The second label has not yet been drawn, meaning I can't determine the size of the frame and thus can not find the proper x position to align all second labels.
I have tried subclassing the UITableViewController and looking at events such as viewDidLoad and viewDidAppear unfortunatly also in these events the cells aren't drawn yet.
What I Want ...
What I want is for the table view to draw the cells at least once so I can determine the sizes of the labels within the table view cell. I thought to accomplish this by looping through all the cells with cellForRow, but although it successfully returns the cell the content is not drawn yet meaning the frame remains with a width of zero.
Does anyone have a solution?
Thanks in advance,
Mark
Try calling sizeWithFont: on the contents of these labels to get the max width before you draw anything. You should be able to use it later in your cellForRowAtIndexPath: to adjust the width as you need.
I would recommend you reconsider using UITableViewCellStyleValue2 cells instead and attempt to configure the textLabel and detailTextLabel. I had a similar situation and this is how I did it.
First off, you really ought to just pick an explicit, fixed position at which the first label ends and the second one begins, based on what you know about the minimum and maximum lengths of the text that will be put in those labels. That would eliminate this problem entirely.
But if you want a solution: use the sizeWithFont: method or one of its cousins (see the Xcode docs). Specifically, loop through the values that will go in the first labels, apply sizeWithFont to each, and keep track of the largest width you see. (I'm assuming you have access to the values before they go in the cells; since they're dynamic, they must be passing through the table view controller, no?)
Now you have the value you seek, without having to perform the extremely wasteful operation of creating a bunch of cell objects and never using them for their intended purpose.
I think what you need to do is to add a viewController to the have the UITableViewController control the UITableViewCell itself so that you can capture the events of the labels loading. The viewController will have references to both labels so it can adjust them accordingly in response to -viewDidAppear.
I've never done this but a UITableViewCell is a view like any other so you should be able to set up a controller for it. You might need to manually activate the controller since you have no navigation controller to do it for you in this context.

Multi-line UITableViewCell using UITableViewCellStyleValue2 style

I'm trying to figure out how to replicate the UITableViewCellStyleValue2 style so that the detail text can be multiple lines - as seen in the 'address' cells in the Contacts app. Like the Contacts app, some of the fields (like street name) are optional; so it would show say 3 lines instead of 4, if the street was not nil.
I'm I missing a trick, or do I have to create a custom cell in IB? How to ensure the text and detail text labels line-up with other UITableViewCellStyleValue2 cells?
Thanks for any tips.
Another round of searching found this:
http://the-lost-beauty.blogspot.com/2009/11/multi-line-uitableviewcell-using.html
Quickly tried it, and it works - just need to set the font size down a bit.
It sounds to me like you'll have to create a custom UITableCell. The only way to ensure the text lines up is to get the margin/text width values correct, which can be done via trial and error, or using a measuring tool such as xScope.
Create a custom cell for you table and place a UILabel and a UITextView inside it. Position the label & text view to match their x,y positions to the other cells you are using in that table. You insert "\n" in the textview's text wherever you want line breaks to occur. You resize the textview height depending on the number of lines in the textview using something like:
CGRect frame = yourTextView.frame;
frame.size.height = yourTextView.contentSize.height;
yourTextView.frame = frame;
return frame.size.height + 20.0; // Pad the cell's height as necessary for your applicaion
I also had the problem that the textLabel and the detailTextLabel had a different position. Solution: For the detailTextLabel use the same height like the textLabel (e.g. 13)

UILabel inside custom UITableViewCell not drawing at the correct size

I have a custom table cell which contains a number of UILabels. At runtime, I am adjusting the height of the labels to fit their contents using sizeWithFont:constrainedToSize:lineBreakMode: and repositioning them accordingly. The last label in the cell contains a large amount of text, causing it to wrap, and I'm having a very odd problem. Although the sizeWithFont call returns the correct size, and I'm setting the UILabel's frame to that height, it draws a couple of lines short. This screenshot illustrates what I'm talking about:
In this example, the height of the full block of text should be 90 (as checked in Interface Builder), and that's what returns from sizeWithFont. It's also the height that the UILabel's frame is set to, which I have verified by logging and also by stopping execution and inspecting the value. However, as you can see, it's clearly not drawing the full 90 pixels high, although it's correctly allocating the space for it (the thin black line above 'Edited' is the table cell border). I'm completely perplexed. If anyone can offer some insight as to why it's behaving this way, I would be very grateful.
At last, a solution!
Turns out that the cell does layout twice -- once during heightForRowAtIndexPath, which is where I tweak all the heights of the subviews and the cell, and later during some untraceable transaction originating in __CFRunLoopDoObservers. How did I trace this? I added a layoutSubviews override to my custom table view cell class so I could breakpoint it.
During the second pass, the last UILabel subview was getting set to a shorter height than I set it to, probably in accordance with some arcane autoresizing rules. (Yes, I tried tweaking all of those settings first, with no success.) As it turns out, merely doing nothing in layoutSubviews disabled this framework behavior, allowing me to completely control how my views draw.
With iOS 8 it doesn't work anymore like this. Implementing layoutSubviews alone doesn't do the trick, because the layout of subviews have already changed when the method is called.
I have found 2 solutions:
adding NSLayoutConstraint to layout the subviews programmatically
implementing subview's layoutSubviews and change the frame
An example für solution 2:
- (void)layoutSubviews
{
[super layoutSubviews];
CGRect frame = self.frame;
frame.size.height = 39.f;
self.frame = frame;
}
I've fought with similar problems. It was to do with other properties being set in previous incarnations of the cell. To find it / prove it I changed the reuseidentifer for the offending cell to make sure it was a unique cell.