我有两个viewControllers。 ViewController1
和ViewController2
。
在viewController1
中,我创建了一个名为UIWebView
的{{1}}。
这是webView
:
viewController1.h
这是#import "viewController2.h"
@class viewController2
@interface viewController1 : UIViewController <UIWebViewDelegate>
{
...
}
@property (nonatomic, strong)UIWebView *webView;
- (void)goToPerc:(float)perc;
:
viewController1.m
这是- (void)viewDidLoad {
...
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
webView.delegate = self;
webView.scrollView.delegate = self;
[self.view addSubview:webView];
...
}
- (void)goToPerc:(float)perc {
CGPoint scrollToPoint = CGPointMake(0, (int)(self.webView.scrollView.contentSize.height * (perc / 100)));
NSLog(@"%@", webView);
[webView.scrollView setContentOffset:scrollToPoint animated:YES];
}
:
viewController2.h
这是#import <UIKit/UIKit.h>
#import "viewController1.h"
@interface viewController2 : UIViewController
{
...
}
:
viewController2.m
...
- (void)blaBla
{
viewController1 *vc1 = [[viewController1 alloc] init];
float scrollToPerc = 50.0;
[vc1 goToPerc:scrollToPerc];
NSLog(@"%@", vc1); // returns viewController1 in log
}
中的NSLog(@"%@", webView);
返回null。滚动显然不起作用。为什么? (void)goToPerc:(float)perc
中的所有其他功能都不会在viewController1
上返回null,webView
上的viewDidLoad
会被调用,因此viewController1
确实存在!
我也试过webView
,也没有成功。
答案 0 :(得分:1)
我认为你正在创建一个新的viewcontroller,insead访问前一个
viewController1 *vc1 = [[viewController1 alloc] init];
float scrollToPerc = 50.0;
[vc1 goToPerc:scrollToPerc];
NSLog(@"%@", vc1);
你可以尝试
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *vc1 = [storyboard instantiateViewControllerWithIdentifier:@"YourSecondviewcontrollerIdentifier"];
float scrollToPerc = 50.0;
[vc1 goToPerc:scrollToPerc];
NSLog(@"%@", vc1);
答案 1 :(得分:1)
因为您没有在导航中推送视图控制器,因此视图可以加载最新的viewController。创建了viewController对象,这就是您能够访问其公共属性或方法的原因。
因此,您可以在blabla方法中使用此方法创建viewController的对象:
viewController1ViewController *vc1 = [[viewController1ViewController alloc] initWithNibName:@"viewController1ViewController" bundle:nil];
和
然后你可以在viewDidLoad
中编写的这个方法中编写所有东西- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
或者如果你想展示你的viewController,你可以使用你的控制器的navigationController属性的pushViewController,如下所示:
[self.navigationController pushViewController:vc1 animated:NO];
这将调用您的viewDidLoad
:
我想它应该清除你的怀疑。
答案 2 :(得分:0)
因为您在代码中创建了webView,所以它只在viewDidLoad中创建。
创建viewController1时,在尝试访问视图之前未加载view
,因此未调用viewDidLoad
,因此不会创建webView。
许多不同的解决方案:
a)直接在viewController1.xib文件中添加webView(并使其成为IBOutlet)
b)创建viewController1后立即访问view
(即:[vc1 view];
)
c)在推送/呈现viewController
之后才调用goToPerc: