UIScrollview 分页中的页面大小不正确

Incorrect Page size in UIScrollview Paging

我想用 UIScrollview 做一个简单的分页,但是页面在第二个屏幕后就出来了。这是我的代码。

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.

    NSArray *colors =[NSArray arrayWithObjects:@"1. This is my first Page ",@"2. This is my Second Page",@"3. This is my third Page",@"4. This is my fourth Page",@"5. This is my fifth Page",nil];

for (int i = 0; i < colors.count; i++) {
    CGRect frame;
    frame.origin.x = (scroll_events.frame.size.width) * i;
    frame.origin.y = 0;
    frame.size = scroll_events.frame.size;
    
    UIView *subview = [[UIView alloc] initWithFrame:frame];
    [self.scroll_events addSubview:subview];
    
        UITextView *myTextView = [[UITextView alloc] init];
        myTextView.text = colors[i];
        [subview addSubview:myTextView];
        [myTextView setBackgroundColor: [UIColor redColor]];
        [myTextView setTextColor: [UIColor blackColor]];
        [myTextView setFont: [UIFont fontWithName:@"Lobster 1.4" size:30]];
        myTextView.frame = CGRectMake(0.0,0.0,scroll_events.bounds.size.width,scroll_events.bounds.size.height);
        myTextView.editable = NO;
        myTextView.selectable = NO;
        myTextView.scrollEnabled = NO;
}
self.scroll_events.contentSize = CGSizeMake(self.scroll_events.frame.size.width * colors.count, self.scroll_events.frame.size.height);
}

这是我的滚动视图的屏幕截图

在 ViewDidLoad 中,您的滚动视图的框架可能仍未设置。

在 ViewDidAppear 中尝试该代码并检查它是否有效。

建议:您应该继承 UISCrollView 并在那里初始化视图,而不是 ViewController。

让我知道它有效!

此致。