Can I access views when drawn in the drawRect method?
When creating the content view of a tableViewCell, I used the drawInRect:withFont, drawAtPoint... and others, inside drawRect: since all I needed was to lay some text. Turns out, part of the text drawn need to be clickable URLs. So I decided to create a UIWebView and insert it into my drawRect. Everything seems to be laid out fine, the problem is that interaction with the UIWebView is not happening. I tried enabling the interaction, did not work. I want to know, since with drawRect: I am drawing to the current graphics context, there is anything I can do to have my subviews interact with the user?
here is some of my code I use inside the UITableViewCell class.-(void) drawRect:(CGRect)rect{
NSString *comment = @"something";
[comment drawAtPoint:point forWidth:195 withFont:someFont lineBreakMode:UILineBreakModeMiddleTruncation];
NSString *anotherCommentWithURL = @"this comment has a URL http://twtr.us";
UIWebView *webView = [[UIWebView alloc] initWithFrame:someFrame];
webView.delegate = self;
webView.text = anotherCommentWithURL;
[self addSubView:webView];
[webView release];
}
As I said, t开发者_如何学JAVAhe view draws fine, but there is no interaction with the webView from the outside. the URL gets embedded into HTML and should be clickable. It is not. I got it working on another view, but on that one I lay the views. Any ideas?
You do not want to be creating a new UIWebView
and adding it as a subview for each call to drawRect:
This is an extremely bad idea:
- It's going to be slow. Those are heavy objects, and you're creating thousands of them.
- You're not getting rid of the old
UIWebView
objects. So you're essentially layering thousands and thousands of them on top of one another.
You should be creating the UIWebView
once, probably in the initializer, or some other method that is only called once. You should also add it as a subview only once.
The act of creating thousands of those views could certainly be causing your problem.
If your view is changing position/size, then you can override setFrame:
and in addition to calling the superclass' method, tweak the frame of the UIWebView
, which you'll definitely want to maintain as an instance variable.
This is wrong. You shouldn't be instantiating UIWebView inside -drawRect: - which is, potentially, called repeatedly to refresh screen.
Instead, you should at least create a subclass of UITableViewCell and add to it a UIWebView to hold all of your text.
Even then, UIWebView is probably too heavyweight to be placed in each cell.
You might want to check this out.
精彩评论