Reputation: 63
enter image description hereWhen i add three imageViews to scrollView, and i setting scrollView contentSize is three times scrollView's width, even if it was appeared in scrolView,but imageView's width not equal to scrollview's. I ensured that already setting they width equeal to each otehr. If who know that how to resolve this issue,please help me, thinks.
- (void)addScrollViewImage {
for (NSInteger index = 0; index < IMAGE_NUM; index++) {
UIImageView *imageView = [[UIImageView alloc] init];
CGFloat imageViewX = index * (self.scrollView.frame.size.width);
imageView.frame = CGRectMake(imageViewX, 0, self.scrollView.frame.size.width , self.scrollView.frame.size.height);
imageView.image = [UIImage imageNamed:@"搜索图片"];
imageView.contentMode = UIViewContentModeScaleAspectFill;
[self.scrollView addSubview:imageView];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * IMAGE_NUM, self.scrollView.frame.size.height);
}
Upvotes: 1
Views: 1361
Reputation: 5215
This is because when your viewController is loaded, view / scrollView frame is still unknown.
You need to override viewDidLayoutSubviews() and setup children frames and content size there.
Important note: iOS is adding EXTRA UIImageView's for scroll indicators. That's why you can't use scrollView.subviews.count inside viewDidLayoutSubviews(), but you can use IMAGE_NUM though.
Some Swift code:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let scrollSize = scrollView.bounds.size
var frame = scrollView.bounds
// Wrong: for i in 0 ..< scrollView.subviews.count
for i in 0 ..< IMAGE_NUM {
let view = scrollView.subviews[i]
view.frame = frame
frame.origin.x += scrollSize.width
}
scrollView.contentSize = CGSize(width: frame.origin.x, height: scrollSize.height)
}
Upvotes: 0
Reputation: 8322
you need to change imageview content mode
imageView.contentMode = UIViewContentModeScaleAspectFill;
With
imageView.contentMode = UIViewContentModeScaleToFill;
Upvotes: 1