我对 UIScrollView 有一个非常奇怪的问题并添加了 UIViewControllers。看起来当 UIViewControllers 添加到 UIScrollView 进行分页时,UIViewController 会丢弃所有添加的对象。
在项目中,我有一个带有两个视图的故事板,它们正确连接到相应的代码。
我知道代码不会将添加的 UIViewController 移动到正确的 X,但在这个测试中,我只添加了一个 UIViewController,所以没关系。
这是滚动代码.h:
#import <UIKit/UIKit.h>
#import "TestViewController.h"
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (strong, nonatomic) NSMutableArray *scrollController;
@end
这是滚动代码.m:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.scrollController = [[NSMutableArray alloc] init];
}
- (void)viewDidAppear:(BOOL)animated {
//just adding two controllers
TestViewController *first = [[TestViewController alloc] init];
[self.scrollView addSubview:first.view];
[self.scrollController addObject:first];
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * self.scrollController.count, self.scrollView.frame.size.height);
self.pageControl.numberOfPages = [self.scrollController count];
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// Update the page when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
这是视图控制器代码.h:
#import <UIKit/UIKit.h>
@interface TestViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *lblMsg;
@end
这是视图控制器代码.m:
#import "TestViewController.h"
@interface TestViewController ()
@end
@implementation TestViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSLog(@"Label: %@", self.lblMsg);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
日志中的输出是:
Label: (null)
任何人都能够看到我做错了什么?