碰到一个很简单的场景:我想把一张图片居中显示在UIScrollView当中。
然后是 ViewController,定义一个imageview属性作为scrollView的subview
@interface BBUViewController () <UIScrollViewDelegate> // 注意这里实现放缩用的delegate
@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
@property (strong, nonatomic) UIImageView *imageview;
@end
最近喜欢上了lazy init,非常推荐使用这种方式,或许这是构造函数后遗症吧,能避免很多遗漏初始化问题,再次推荐。imageview的getter,这个不再写setter了。因为很简单,系统自己生成的就好。用了一张图片findme.png生成UIImage
- (UIImageView *)imageview
{
if (!_imageview) {
_imageview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"findme"]];
}
[_imageview sizeToFit];
return _imageview;
}
- (void)setScrollview:(UIScrollView *)scrollview
{
_scrollview = scrollview;
// 放缩比例
_scrollview.minimumZoomScale = 0.2;
_scrollview.maximumZoomScale = 2.0;
_scrollview.delegate = self;
// contentSize一定不要忘记,否则imageView不会出来
_scrollview.contentSize = self.imageview.image ? self.imageview.image.size : CGSizeZero;
// 把content,也就是imageView,移动到中间
[_scrollview setContentOffset:CGPointMake((_scrollview.contentSize.width - _scrollview.bounds.size.width) * 0.5,
(_scrollview.contentSize.height - _scrollview.bounds.size.height) * 0.5) animated:YES];
}
下来可以viewDidLoad了,很简单
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.scrollview addSubview:self.imageview];
}
好像可以生成上图中图2的效果了,居中显示。
但是~ 换成4寸屏幕就是悲剧!
图片直接跑到左上角了。
算了,今天好累不卖关子了,把scrollview的setter里居中取消掉,然后在viewDidLoad里面给self.imageview指定中心点。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self setImageviewCenterInScrollView:self.scrollview];
[self.scrollview addSubview:self.imageview];
}
#pragma mark - self defined
-(void)setImageviewCenterInScrollView:(UIScrollView *)scrollView
{
CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
(scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
(scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
// setCenter!!!!!!!!
self.imageview.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
scrollView.contentSize.height * 0.5 + offsetY);
}