Lawrence413
Lawrence413

Reputation: 2016

UITableViewCell drawRect() Override Makes Device Really Slow (CPU Usage Spike)

That's pretty much my issue. I want to create rounded plain cells in a table view. I override drawRect(frame: CGRect) in a TableViewCell class, but when the cell is shown, the device (simulator too) freezes for about 1 second and the debugger shows a spike in CPU usage to 75%.

Not that it might be of any use, but here's my code:

    override func drawRect(rect: CGRect) {
    frame.origin.x = 10
    frame.size.width -= 20
}

So is there any easier/MUCH more efficient/"legal"(somebody said overriding drawRect is considered "hacky") way of simply making every cell narrower than the screen?

Upvotes: 1

Views: 495

Answers (1)

thelaws
thelaws

Reputation: 8001

You're not really allowed to use drawRect to modify a view's frame. drawRect just gives you an opportunity to draw within the given frame.

The actual frame of a UITableViewCell is managed by the UITableView through it's width and the heightForRowAtIndexPath: method. Also, the table view is very efficient at caching and reusing cells. Unless you are displaying 1000's of cell on the screen, you won't need to worry about the efficiency of the drawing.

I think you should be adding a subview to the cell's contentView, and setting it's frame as inset to the cell. This can be done using autolayout in a custom cell xib, or manaully in cellForRowAtIndexPath:.

Upvotes: 1

Related Questions