问题
I am trying to draw a checkbox triangle in a UITableViewCell. In the Data Source protocol method -tableView:cellForRowAtIndexPath: I have added the following in the code bloc which asks if the cell is nil:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextMoveToPoint(context, 75,10);
CGContextAddLineToPoint(context, 10, 150);
CGContextAddLineToPoint(context, 160, 150);
CGContextClosePath(context);
[[UIColor blackColor] setStroke];
CGContextStrokePath(context);
When executing the code, I get a series of 'invalid context 0x0' messages on the following methods: CGContextBeginPath: CGContextMoveToPoint: CGContextAddLineToPoint: (twice) CGContextClosePath: CGContextSetStrokeColorWithColor: CGContextDrawPath
The messages repeat for each TableViewCell row in my table.
Am I not able to draw triangles or other geometric shapes within customizedUITableViewCell objects?
回答1:
UIGraphicsGetCurrentContext() will not return a valid context if called outside drawRect:. You have to do your custom drawing in a view's drawRect: method. For your purpose, you should probably create a custom UIView subclass for your checkbox and add that view as a subview to the cell.
来源:https://stackoverflow.com/questions/5552210/uitableviewcells-invalid-context-trying-to-draw