Too many UILabels with unicode text - iphone

I have 180 UILabels (subviews of UITableViewCells) in an iPad app with 155 width X 155 height for each UILabel, and each one contains a big amount of Unicode text (Arabic language), when I scroll down the TableView it hangs for 1 second and then keeps scrolling normally, this happens with every scroll attempt by the user and this is tested on iPAD2 device.
however, when I changed the text to English language (also big amount of English text), the TableView does not hang and scrolls normally.
anyone got an idea on how to solve this issue with Unicode text ?
thank you so much in advance.
EDIT:
the code is large to fit here, so in brief, I create each UILabel with a loop like this: [[[UILabel alloc] initWithFrame:CGRectZero] autorelease]; in cellForRowAtIndexPath method, then play with the frame later in the same method according to interface orientation, after that I add each UILabel to the cell like this: [cell.contentView addSubView:myLabel]; . each cell contains 4 of these 'UILabels', so I have a total of 45 cells, nothing more, straight forward and simple code.

The use of unicode shouldn't be the problem here, as it will render at similar speeds to any other text.
There are possibly a few issues that are slowing down your code. First of all, you should attempt to use UITableView's native cell reuse, add the labels to the UITableViewCell and then dequeueWithResusableIdentifier them. You should only generate your labels when that method returns nil and you have to create a new UITableViewCell (it's unclear from the original question if you do this already).
One other thing you can do after this to make sure as many of your views are opaque as possible to speed up compositing. Instruments includes an option to tint non-opaque views to make this easier.

There are many ways you can optimize your code:
One check if your app is not leaking. Proper release of labels.
Use reusability of cells. I dont know if you are using that or not.
Since every time you scroll your cellForRowAtIndexPath delegate method is called.
In case you dont know about reusability try this link.

Related

Where is UITableViewCell being put back to queue?

I am currently working on update to an app that I didn't make myself.
In it, there is a highly customized table view that is used for horizontal scrolling through images with 3 images showing at once and enabled paging.
The issue is that sometimes they appear white and I think that is because they are returned by dequeueReusableCell while they are still visible. (So table view is reusing the cell that, because is still visible, shouldn't be reused.)
Since there is usually not very many cells in that table, I tried with a workaround that alloc's and init's a new cell every single time instead of dequeuing an old one and so far it works fine (for a small table).
However, this is not a good solution and I want to do it the "right" way.
I don't know how is it decided whether cell should be put back to queue or not.
What should I do to stop cells from being queued for reuse?
If you really don't want the cells to be reused, do it the way you already did. It is not recommended to be not reusing UITableViewCells. The reusing-technique saves memory.
But when you tableView is not highly memory-expensive, do it like this. It is the way not "disable" reusing.
It sounds like it's because the tableView is rotated by 90° to achieve horizontal scrolling. So iOS thinks that the cell which got scrolled an amount out x pixels and must be located offscreen and can be reused. This is what I presume.
When your update addresses iOS 6.0 and later I'd recommend switching to UICollectionView which is very similar to UITableView but has the ability of totally customized flow layouts (this is the term you'd google for).
When my presumption is correct, another possible solution could be to use two reusable IDs and alternate them so that a cell got enough "space" to scroll:
if([indexPath row] % 2 == 0) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierOne];
}
else {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierTwo];
}
But I REALLY don't now if I'm right with this guess :)

What is an acceptable FPS for scrolling, and what are tips for improving performance?

I see in many WWDC video's that says you want to achieve 60.0 FPS as close as possible to get a better smooth scrolling experience. I have a UIScrolLView which loads up image and a couple of table view's at once. Currently I am getting 30 FPS. This is half of what the recommended FPS. Just wondering what FPS do you guys typically get for a table view/scroll view that loads up images and other heavy stuff/rendering stuff.
Any other tips for optiziming FPS? I've spend the past week till now firing up Instruments using the time profiler, allocations, and core animation tool to optimize as much as I can.
Just to clarify a bit on what I have. I have a masonry/waterfall/pinterest style layout on the iPad. So it's not just a regular UITableView. It's a UIScrollView that fills out the whole screen, and is filled with a couple of UIView's. Each of this view has a 150x150 UIImageView and a UITableView and also it has some attributed label, drawn using Core Text. So at one glance when you see the screen, you can see 5-8 table view at one shot, each cell again has a UIImageView and then each cell renders attributed label drawn using core text.
So you can just image how deep and complicated this is. This is not just a regular table view with a UIImageView. I know how to get 60 FPS with just one UITableView in an iPhone with a UIImage. The concept is to load images asynchrounously and not to block the main thread as much as possible.
EDIT:
It seems that the problem here is the UITableView that I have inside my view.. when I remove that from the UIView I get really smooth scrolling..
I uploaded a sample project which is a simpler version of what I have, but it clearly shows the problem. The link is here
Many things affect render performance, here are some items you can check:
Profile - You said you already did this, so great job! Unfortunately profiling is often overlooked, even though it can reveal unexpected problems. In one app I was working on a calendar with different cells representing dates. At first scrolling between cells slow, which was unexpected. I thought maybe it was drawing a few cells too many. After profiling I found that [NSCalender currentCalender] was using 85% of my CPU time! After fixing that everything scrolled great!
Images - Large images put a lot of load in CoreGraphics. Scrolling especially requires a lot of draw operations to move them around. One tip is to scale images on the device as little as you can, that makes CoreGraphics' job a lot easier. If an image is twice as large as the view displaying it, resize the UIImage before displaying it in the view. iOS devices handle PNGs best. They are compressed by a tool (pngcrush) at compile time and iOS has special hardware for rendering them.
Edit: JPGs are probably a better option for photos. iOS devices have dedicated JPG decoders as well.
Custom Drawing - If possible, cutback on the amount of custom CGContext drawing you do. Lots of custom drawing has negative effects on animation speed. I would considering using an image over complex custom drawing, if possible.
Cull - Only draw things you need to. UITableView automatically unloads and loads cells as they appear, so this is done for you, but any custom CGContext drawing should only be done when that part is visible. Also automatic view shadows can be very slow in my experience.
Reuse - Use the reuse identifier on UITableView, this will allow UITableView to reuse cell objects rather than reallocating as it scrolls - look at the answer to this question. Also reuse UIImages rather than allocating multiple for the same file. imageNamed caches images automatically but imageFromContents of file does not.
Create your own - You could create your own grid view class that culls it's subviews views hidden off screen, and scrolls with lazy content loading. By writing a custom solution you can fully control the process and create a design optimized for the usage context. For most use cases you will have a hard time building something better than the Apple standard, but I have seen it done in specific cases.
Last resort - Reduce the size of the offending view (improves filtrate), break content into multiple pages, downsize images, cut out older devices that don't perform as well. I would settle for 30 FPS before sacrificing most of that stuff. Devices will continue to get faster, older devices will be eliminated, and your app will gradually get faster.
I get close to 60 fps with my UITableViewController where the table contains about 2000 cells and each cell pulls an image from the web. The trick is to lazy load the images as you need them. This sample code from Apple is pretty helpful.
The general idea is to keep the UI responsive by not blocking the main thread. Perform downloads and other time-consuming tasks on another thread.
I would do something called Lazy Loading, which doesn't load the images until they are actually seen.
Here's a great example on how to do so: http://www.cocoacontrols.com/platforms/ios/controls/mhlazytableimages
Good Luck!
What I've done is to use NSCache. I've created a small class with properties that conforms to the NSCache data protocol (its really easy to do). So what I do is create a relationship between each cell in the main table and various things worth caching: NSAttributed strings, images etc - really anything that takes work to create. I don't preload it but you could.
When you are asked to provide a cell by the tableview, look in your cache for your primary object. If there, pull all all the objects you need. If the cache does not have the object, then get the data the old fashion way, but before you finish, save it in the cache too.
This really helped me reduce "stutter" when scrolling the cell. Also, do NOT animate anything in the cell - that kills performance. Everything should be fully rendered.
Another thing to remember - make sure ever view which can be set to opaque has its property set to YES. That for sure helps the system render the cell (including the backgound view if you use one.)
EDIT:
So you provided information that included UITableViews may the root problem. So two suggestions:
1) Can you step back and figure out how to make the scrollView a single UITableView? With table headers and footers, and section headers and footers, and even the ability to essentially make a cell a floating view, can't you figure out how to rearchitect what you have?
2) So you decide no to suggestion 1. Then, do this. Think of the space used by the tableview as being a container view. Whenever the tableview is edited, take an image snapshot of it and keep this image around. As soon as the user starts to scroll, swap the tableViews out for the images. When the scrollView stops swap the UITableView back in. This of course will take some fine tuning. In fact, you could probably overlay an opaque image snapshot over the table (which will hide it and prevent it from being asked to draw itself) during scrolling.
the human eye sees at about 60 FPS, so that's why it's recommended, but 30 FPS will also appear very smooth, especially when a regular user is viewing it, as opposed to you trying to find as much to fix as possible. This is obviously dependent on how fast the scrolling goes, if the difference from frame to frame is a movement of a few pixels, 30 FPS will do just fine, but faster movement will require a higher FPS to appear smooth
There are a few things you can do in general to get better table view performance:
1) Switch to Loren Brichter's method of drawing UITableViewCell's (for lack of a better link: http://www.therefinedgeek.com.au/index.php/2010/12/21/fast-scrolling-uitableview-updates-for-ios-4-2/)
Basically, all his code does is render all your cell content as one opaque UIView, which UITableView (and CoreGraphics) can very quickly blast onto a UITableViewCell
If you don't want to do all your cell design in drawRect:, you can still use nibs, but:
Make sure every subview is marked opaque
Don't have any transparent/semi-transparent subviews
Don't have any images with an alpha channel != 1.0f.
2) Don't let UIImageView do any scaling to display your image, give it a correctly-sized UIImage
3) If you're using iOS 5 and above, you can register a nib for a particular cell identifier. That way, when you call [tableView dequeueReusableCellWithIdentifier:], you are guaranteed to get a cell. Cell allocation is faster (according to Apple), and you get to write less code:
- (void)viewDidLoad {
UINib *nib = [UINib nibWithNibName:#"MyCell" bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:#"MyCellIdentifier"];
}
// ...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"MyCellIdentifier";
MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// Commented out code is no longer needed
//if (cell == nil) {
// cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
//}
// setup cell
return cell;
}
4) Displaying images downloaded from the web
Display a default image (something to look at while the real image is downloading)
Start the download on a separate thread (hint: use GCD's dispatch_async())
When the image comes in, cache it (hint: NSCache), and display it on the cell
Do all image downloading/caching off the main thread; the only thing you should be doing on the main thread is setting the image (remember UI code HAS to be on the main thread!)
You'll probably want to write an async-capable UIImageView (or use an existing library).
Stay away from EGOImageView, even though it has async downloading, it does cache lookup (which happens to be on disk, so that means costly disk IO) on the main thread before dispatching to a background thread for the download. I used to use it, but I ended up writing my own set of classes to handle this, and it's significantly faster.
-
Just follow these, and stuff other ppl have written here, and you'll have table views that scroll like glass in no time :)
You want 60fps, but 30 fps doesn't look too terrible in actuality. But I would try to achieve 60fps for a smoother look while scrolling.
There are many Performance Improvement possibilities, that are also shown by various tutorials
While 60 FPS is the ideal, games like Halo run very prettily in 30 FPS. The battlefield chaos in Halo probably involve more surprising, rapid motion than most lists, even complex ones like yours!

UITableView scrolls choppy when the UITableViewCell is big

First, I know there are a few answers here on S.O. that addresses the choppy uitableview issue.
Some of them i applied in my code (namely the cell.layer.shouldRasterize = TRUE in particular as well as the cell queue caching thing).
My choppiness is observed to be due to large cell rows (70 pixels height).
If I change the row height to be 20, then it scrolls smooth as butter.
But 30 and above, it gets choppy, especially when i "pull" and "let go" of the table so that it bounces back into place.
One thing that i am NOT doing is flattening the view (I am using the cell's Xib).
Would doing away with the xib design view give me the performance boost that I need?
Also, any ideas why a 30+ pixel height cell row is causing such a drastic difference compared to the smooth-as-butter 20 pixel height?
Note: Even if i make everything in the cell xib to be hidden, i still get choppiness at 70 pixel height.
Check out the example from Apple - TableViewSuite. Look at the fifth example which shows hot to make a very fast cell with images and labels. Also note that cells created using xibs are much slower. So avoid subviews and perform custom drawing in drawRect method. Everything is shown in the apples example:
http://developer.apple.com/library/ios/#samplecode/TableViewSuite/Introduction/Intro.html

How Can I Recreate This UITableView Look?

Right now I have a standard UITableView that is empty by default and the user can add cells to it.
I noticed this app starts with no cells and is empty (like you cant see lines) but my standard view always has the lines like standard table view.
I thought it may be a grouped table style but the edges are not curved like the grouped style is.
Does anyone have any ideas?
The lines between cells are controlled by the separatorStyle property of your tableView. To remove the lines simply set:
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
Your other options are UITableViewCellSeparatorStyleSingleLine and UITableViewCellSeparatorStyleSingleLineEtched.
You can hide the separator lines by setting their color to the same color as your background, e.g.
tableView.separatorColor = [myApp theColorOfMyBackground]; // A UIColor object
Make sense?
The cells in your picture are likely custom cells, but you didn't really ask about that. :-)
EDIT: As noted in another answer seperatorStyle can be used to simply "turn off" the lines. That's a better way to do it.
This is a good question. +1 What app is this? Does the view you show above actually "scroll" even though only 2 rows are showing? I am wondering if it is a truly a table view. It could be a series of UIViews added to a UIScrollView with a dark background.
Assuming the programmer knows how tall the "rows" are, then they can add them with a pixel spacing over the charcoal background. With the UIScrollView, the programmer can define the contentSize.
If more views were added to extend past off the screen and the contentSize was appropriately defined, the USScrollView would automatically allow scrolling at that point.
Selecting a "row" could be easily handled by UIGesture controls on each UIView.
*EDIT
After seeing the app, Delivery by JuneCload, it is definitely using a UITableView with custom cell views. As Mark and Matt have answered.

Adding a dynamic-height UITableView into a scrolling view?

Hello all – I'm getting into iPhone development and have hit my first confusing UI point. Here's the situation:
My app is tab-based, and the view that I'm confused about has a static featured content image at the top, then a dynamic list below into which X headlines are loaded. My goal is to have the height of the headline table grow as elements are added to it, and then to have the whole view scroll (both featured image on top and headline list below). So, I guess my question comes in two parts:
1) First, how do you set up a dynamic-height table view that will grow as cells are added to it. So far I've only been able to have my tables handle their own scrolling.
2) Then, what is the root NIB view that the featured image and the table should live in to enabled scrolling? I've dropped oversized content into a UIScrollView now, although did seem to have any success with having it automatically scroll.
Thanks in advance for any help on this subject!
To the first:
As i understand your situation:
You want to add a image to the top of the UITableView and the image should scroll with the UITableView, shouldn't?
The UITabeView has a property called tableHeaderView. It's just a view, so you can set a UIImageView to it.
(I have no xCode at the current time, you need to edit the code)
UIImage *image = [UIImage imageNamed:#"myCoolPic.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame =CGRectMake(0,0,width,height);
tableView.tableHeaderView = imageView;
[imageView release];
What you're asking is probably doable with Interface Builder (or not, I don't know) but I know the code way to do it.
To change the height of the table all you do is set the frame of the UITableView object. The default height of a UITableViewCell is 44 I believe, so set it to multiples of that depending on how many cells you have. Of course your cells can be any height so you will need to keep track of what you report in heightForRowAtIndexPath and set the table frame accordingly.
UITableView will certainly live in a UIScrollView and both components can scroll. The table view needs to become a subview of the scroll view, so does the image. Then you will scroll the table if you drag on it directly or scroll the scroll view if you drag the image or the scroll view.
For the first question, I'm a little confused by the way you ask it: "how do you set up a dynamic-height table view that will grow as cells are added to it." Table views have a function that it calls before the table is fully loaded with data called "numberOfRowsInSection." So the number of cells is based on that function, and should you update the variable used to determine the return value of that function (usually [myArray count]) it should automatically find the right size for the whole table.
However, variable height cells are something that I found kinda tricky and I've solved it using the following:
There are some UIKit NSString additions that you might find useful.
http://developer.apple.com/iphone/library/documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html
Particularly the sizeWithFont: functions.
Table views also have a 'heightForRowAtIndexPath:' function that is called 'numberOfRowsInSection' amount of times. Each call determines the height of the cell at the indexpath.
So, for example: (assuming myArray is an array of NSStrings)
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return [[myArray objectAtIndex:indexPath.row] sizeWithFont:myFont];}
This will return a height based off of your actual data, piece by piece. There are other functions to specify how the text wraps and truncates, etc. as well.
It doesn't feel like a great solution because you end up fetching your data twice, once to determine the height, and then again when you configure the cell in 'cellForRowAtIndexPath:' However, it does work!
I've learned a lot in the past few weeks and have gone through a few iterations of addressing this problem. My first solution was to manually measure the table height, then set the table rect to display at that height, and finally to set the scrollView's content rect to encompass the the table and top feature. What that solution did basically work, I started encountering some display issues when branching out into new views with different toolbar configurations. It seemed that my manual frame size was interfering with iPhone's native content scaling.
So, I scrapped the manual sizing and went to just making that top feature block be a custom table cell that displayed within its own section at the top of the table. I made a hard logic definition that section 0 only had one table cell, and that cell was my custom layout that I linked in through Interface Builder. I was then able to get rid of ALL my messy custom scaling logic, and the whole system is cleaner, smoother, and works reliably.