在viewDidLoad中我将按钮添加到循环内的滚动视图中,如下所示:
for (int i = 0; i < self.topics.count; i++) {
id obj = self.topics[i];
if ([obj isKindOfClass:[TRBTaxonomy class]]) {
TRBTaxonomy *topic = obj;
UIButton *prevTopicButton = nil;
if (i > 0) {
prevTopicButton = buttons[i-1];
}
//Create topic divider
UILabel *topicsDividerLabel =[[UILabel alloc] init];
[topicsDividerLabel setBackgroundColor:[UIColor lightGrayColor]];
[topicsDividerLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
UIButton *topicButton = [UIButton buttonWithType:UIButtonTypeSystem];
topicButton.translatesAutoresizingMaskIntoConstraints = NO;
[topicButton setTitle:topic.name forState:UIControlStateNormal];
[topicButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
topicButton.titleLabel.font = [UIFont fontWithName:(NSString*)[[TRBUtils fonts] valueForKey:@"TopicsBarFontName"] size:15];
topicButton.titleLabel.textAlignment = NSTextAlignmentLeft;
[topicButton addTarget:self action:@selector(topicTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:topicButton];
}
}
然后,在循环结束时,我尝试获取滚动视图内容的宽度,将其放置在滚动视图中的中心水平位置:
CGFloat newContentOffsetX = (self.scrollView.contentSize.width/2) - (self.scrollView.bounds.size.width/2);
self.scrollView.contentOffset = CGPointMake(newContentOffsetX, 0);
但此时 self.scrollView.contentSize.width 返回0
当我从viewDidAppear获取内容时,有一个内容,一切正常,但是滚动视图内容从左侧移动到中心时会出现明显的闪烁。
如何摆脱这种眨眼?为什么self.scrollView.contentSize.width在viewDidLoad和viewWillAppear上为零但在viewDidAppear中没有?
答案 0 :(得分:0)
为什么self.scrollView.contentSize.width在viewDidLoad和viewWillAppear上为零,但在viewDidAppear中没有?
当调用方法viewDidLoad
和viewWillAppear
时,视图才会显示。所以contentSize
为0应该不奇怪。
如何摆脱这种眨眼?
尝试使用此方法
- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated
CGFloat newContentOffsetX = (self.scrollView.contentSize.width/2) - (self.scrollView.bounds.size.width/2);
[self.scrollView setContentOffset:CGPointMake(newContentOffsetX, 0) animated:YES];