I'm working on an iPhone project where I'v开发者_StackOverflow社区e inherited someone else's code. I have a situation where viewController A has a UIWebView and it is set as the delegate of that UIWebView.
I also have a Class B which is set as the delegate of viewController A.
In an instance of B I want to send some javascript using stringByEvaluatingJavaScriptFromString to the UIWebView in viewController A.
What's the best way of doing it?
You could make viewController A a delegate of Class B so that from Class B you can call a method on viewController A where the UIWebView could then execute the desired javascript.
@protocol ClassBDelegate
- (void) executeJavascript:(NSString*)jsString;
@end
@interface ClassB : NSObject<ViewControllerADelegate>
@property (nonatomic, assign) id<ClassBDelegate> delegate;
@end
@implementation ClassB
- (void) myFunc
{
...
[self.delegate executeJavascript:@"alert('Awesome!');"];
}
@end
Some things are missing above like where your instance of class B has it's delegate property assigned to viewControllerA.
You would also need something like:
@interface ClassA : UIViewController<ClassBDelegate>
...
- (void) executeJavascript:(NSString*)jsString;
@end
@implementation ClassA
...
- (void) executeJavascript:(NSString*)jsString
{
[self.myWebView stringByEvaluatingJavaScriptFromString:jsString];
}
@end
Manipulating UIElements should be left to the view controller that owns the UIElement, so for this reason I propose using a delegate. With a reference to viewController A you could directly manipulate the UIWebView, but I'd strongly advise against this. With code like this going on, who knows what other classes are also making changes on UIElements.
加载中,请稍侯......
精彩评论