I am adding a series of UIImageViews to a UIScrollView and I am failing as stuff is not getting centered vertically or horizonatally.
I have tried the following approach and It does not seem to be working:
In my UiTableViewController viewdidLoad:
UIImage *waitingImage = [UIImage imageWithContentsOfFile:pathOfNoImageFile];
UIImageView *imageview = [[UIImageView alloc] init];
[imageview setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:waitingImage];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
self.scrollview.imageview = imageview;
[self.scrollview addSubview:imageview];
I am using a custom UIScrollview so that it can do the centering:
header
#import <UIKit/UIKit.h>
@interface ListingDetailScrollViewController : UIScrollView
@property (nonatomic, retain) UIImageView *imageview;
@end
implementation
#import "ListingDetailScrollViewController.h"
@implementation ListingDetailScrollViewController
@synthesize imageview=_imageview;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
- (void)layoutSubviews {
[super layoutSubviews];
// center the image as it becomes smaller than the size of the screen
CGSize boundsSize = self.bounds.size;
CGRect frameToCenter = self.imageview.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
frameToCenter.origin.x = 0;
// center vertically
if (frameToCenter.size.height < boundsSize.height)
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
frameToCenter.origin.y = 0;
self.imageview.frame = frameToCenter;
}
@end
Any tips or thoughts?