I have a UICollectionView with a custom cell. I had this working completely till I tried to create the collection view programmatically rather than from the storyboard. I did this because I was not able to change the frame size of the collection view for different screen sizes. So I tried to create a collection view programmatically. My problem is my custom cells are not working.
For my custom cells I draw a circle in the view, user cornerradius on the view of the cell, have a UILabel and a UIImageView.
I draw the circle and the perform the cornerradius thing in the drawRect: of the custom cell. The rest i.e: put image in ImageView and text in UILabel, I do it in the collectionView datasource method.
The problem I am having is I don't get the cornerradius thing working although weirdly enough I can draw a circle on the view. second problem is I don't get the image in the image view and no text in the label
Here is my code. I create the collection view in ViewDidload: method.
[layout setSectionInset:UIEdgeInsetsMake(24, 10, 24, 10)];
[layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[layout setMinimumLineSpacing:15];
[layout setMinimumInteritemSpacing:10];
self.collectionView = [[UICollectionView alloc]initWithFrame:rect collectionViewLayout:layout];
self.collectionView.delegate=self;
self.collectionView.dataSource=self;
[self.collectionView registerClass:[customCell class] forCellWithReuseIdentifier:#"cell"];
self.collectionView.backgroundColor= [UIColor blackColor];
self.searchBar.delegate = self;
self.locations = [[NSArray alloc]init];
self.location = [[NSString alloc]init];
[self.view addSubview:self.collectionView];
Here is the drawRect: for my customCell.m
- (void)drawRect:(CGRect)rect
{
UIBezierPath *circularpath = [[UIBezierPath alloc]init];
CGRect Rect = CGRectMake(6, 20, 130, 130);//338
CGPoint mypoint = CGPointMake(Rect.origin.x + (Rect.size.width / 2), Rect.origin.y + (Rect.size.height / 2));
NSLog(#"Circle center point::%f, %f", mypoint.x, mypoint.y);
circularpath = [UIBezierPath bezierPathWithOvalInRect:Rect];
circularpath.lineWidth = 3.0;
[[UIColor whiteColor]setStroke];
UIImage *ori = [UIImage imageNamed:#"drogba.jpg"];
UIImage *image = [[UIImage alloc]initWithCGImage:ori.CGImage scale:1.45 orientation:UIImageOrientationUp];
[[UIColor colorWithPatternImage:image]setFill];
NSLog(#"Circular path:%#", circularpath);
//this works
[circularpath stroke];
//this does not
self.viewForBaselineLayout.layer.cornerRadius = 8.0f;
}
and here is my datasource method
customCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cell" forIndexPath:indexPath];
UIImage *image = [[UIImage alloc]init];
if([self.allInfo count]>0){
image = [self getImageForLocation:[self.allInfo objectAtIndex:indexPath.item]];
NSDictionary *dict = [[NSDictionary alloc]initWithDictionary:[self.allInfo objectAtIndex:indexPath.item]];
NSDictionary *city = [dict objectForKey:#"city"];
NSString *name = [[NSString alloc]initWithString:[city objectForKey:#"name"]];
cell.locationLabel.text = name;
cell.imageView.image = [self getImageForSky:dict];
cell.viewForBaselineLayout.backgroundColor = [UIColor colorWithPatternImage:image];
cell.tempLabel.text = [self getTempForLocation:dict];
}
NSLog(#"image description:%f", image.size.height);
count =1;
return cell;
I don't think it is a problem with my data because all I changed is creating Collection view programmatically rather than using storyboard.
EDIT::
I had to alloc init the image view and the labels for the custom cell and then add them as subview. now 3 of my 4 problems are solved. I still cannot get the corner radius to work for me. I want a slightly curved border for my cell
So firstly, because I removed the cell from the storyboard, I had to add the views to the cell's view as subview. Secondly, to get the rounded corners, I had to also set masksToBounds to YES All this had to be done in the initWithFrame: method of the custom cell. Here the code snippet
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.imageView = [[UIImageView alloc]init];
self.imageView.frame = CGRectMake(26, 27, 90, 90);
self.tempLabel = [[UILabel alloc]initWithFrame:CGRectMake(26, 125, 90, 21)];
self.locationLabel = [[UILabel alloc]initWithFrame:CGRectMake(11, 156, 121, 21)];
self.tempLabel.textAlignment = NSTextAlignmentCenter;
self.tempLabel.textColor = [UIColor whiteColor];
self.locationLabel.textAlignment = NSTextAlignmentCenter;
self.locationLabel.textColor = [UIColor whiteColor];
[self.viewForBaselineLayout addSubview:self.imageView];
[self.viewForBaselineLayout addSubview:self.tempLabel];
[self.viewForBaselineLayout addSubview:self.locationLabel];
self.viewForBaselineLayout.layer.masksToBounds = YES;
self.viewForBaselineLayout.layer.cornerRadius = 8.0f;
}
return self;
}
You have init method in Your custom cell
- (id)initWithFrame:(CGRect)frame
change corner radius in this method.
P.S. Works for me.
Related
I am trying to implement some drawing in custom UITableViewCells. To do that, I have added custom UIView subclass to my cell and implemented the drawing in drawRect method of the custom UIView subclass.
Here's my approach:
I have a UITableView with custom UITableViewCells.
I have subclassed UITableViewCell but the design is implemented directly in my storyboard. The contents of the cell are standard elements (UILabels & UIImageViews) and one custom uiview subclass.
I have set up everything in storyboard using constraints & autolayout.
The custom uiview subclass contains drawing code inside the drawRect method.
The drawing will have to be customized based on some parameters for each UITableViewCell.
Question is, what is the proper way to customize the UIView subclass.
At the moment all I get is a black cube, and I cannot see any drawing... The background color doesn't change and the text does not appear (draw).
EDIT:
In cellForRowAtIndexPath I create the custom UIView using its initWithText: andColor: method:
- (instancetype)initWithText:(NSString *)text andColor:(UIColor *)color
{
NSParameterAssert(text);
self = [super init];
if (self)
{
self.text = text;
[self setBackgroundColor:color];
}
return self;
}
-(void)setBackgroundColor:(UIColor *)backgroundColor
{
self.circleColor = backgroundColor;
[super setBackgroundColor:[UIColor clearColor]];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
[self.circleColor setFill];
CGContextAddArc(context, CGRectGetMidX(rect), CGRectGetMidY(rect),
CGRectGetWidth(rect)/2, 0, 2*M_PI, YES);
CGContextFillPath(context);
}
- (void)drawSubtractedText:(NSString *)text inRect:(CGRect)rect
inContext:(CGContextRef)context
{
CGContextSaveGState(context);
CGContextSetBlendMode(context, kCGBlendModeDestinationOut);
CGFloat pointSize = 8;
UIFont *font = [UIFont boldSystemFontOfSize:pointSize];
CGContextTranslateCTM(context, 0,
(CGRectGetMidY(rect) - (font.lineHeight/2)));
CGRect frame = CGRectMake(0, 0, CGRectGetWidth(rect), font.lineHeight);
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.font = font;
label.text = text;
label.textColor = [UIColor redColor];
label.textAlignment = NSTextAlignmentCenter;
label.backgroundColor = [UIColor blueColor];
[label.layer drawInContext:context];
CGContextRestoreGState(context);
}
You would have given tags in your storyboard for the Label and Image. Use those tags and get the reference of subviews as below
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//some code
UILabel* cellDate = (UILabel *)[cellRef viewWithTag:1]
UIImageView* imageView = (UIImageView *)[cellRef viewWithTag:2]
//some code
}
What you are doing is wrong. You already added UIView reference in story board UITableviewCell. And again you are creating a object for the same custom UIView class in cellForRowIndexpath method. What you can do is, remove the UIView from storyboard and in cellforrowindexpath method like shown below.
CustomUIClass * c = [[CustomUIClass alloc] init];
c.frame = CGRectMake(X, Y, Width, height);
[cell.contentView addSubview:c];
Here add your own frame values to prepare CGRect.
I'm creating a scrollView programmatically, and all the views in it. However, when I add more then 1 view, the other views layers don't show up right in their respective frames.
For example:
-(void)viewDidLoad {
[super viewDidLoad];
self.scrollView = [[UIScrollView alloc] init];
self.scrollView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, 150*5);
self.scrollView.backgroundColor = [UIColor lightGrayColor];
self.scrollView.scrollEnabled = YES;
self.scrollView.showsVerticalScrollIndicator = NO;
[self.view addSubview:self.scrollView];
[self setUpLogInButtons];
}
Then I set the subViews to scrollView up here:
-(void)setUpLogInButtons {
CGFloat subviewWidth = self.scrollView.frame.size.width/2;
CGFloat subviewHeight = 150;
UIView *facebookView = [[UIView alloc] init];
facebookView.frame = CGRectMake(0, 0, subviewWidth, subviewHeight);
[facebookView.layer insertSublayer:[self gradientLayerForViewFrame:facebookView.frame withColors:[self colorArrayWithValues:0x4A5C81 v2:0x495B82 v3:0x495B82 v4:0x475B85 v5:0x465B87 v6:0x455A88 v7:0x445A8A v8:0x435A8B v9:0x425A8D v10:0x41598F v11:0x405990 v12:0x3F5992 v13:0x3E5993 v14:0x3D5895 v15:0x3C5896 v16:0x3B5898 v17:0x3A589A]] atIndex:0];
[facebookView addSubview:[self label:self.facebookLabel forView:facebookView withName:#"Facebook" loggedIn:NO]];
[self.scrollView addSubview:facebookView];
}
When it's one subView it works fantastic, when I add the other one it's not right:
-(void)setUpLogInButtons {
...
UIView *facebookView = [[UIView alloc] init];
...
[self.scrollView addSubview:facebookView];
UIView *twitterView = [[UIView alloc] init];
twitterView.frame = CGRectMake(subviewWidth, 0, subviewWidth, subviewHeight);
[twitterView.layer insertSublayer:[self gradientLayerForViewFrame:twitterView.frame withColors:[self colorArrayWithValues:0x2BA8D5 v2:0x28A8D6 v3:0x25A8D8 v4:0x22A8D9 v5:0x20A9DB v6:0x1DA9DC v7:0x1AA9DE v8:0x18AADF v9:0x15AAE1 v10:0x12AAE3 v11:0x10ABE4 v12:0x0DABE6 v13:0x0AABE7 v14:0x08ACE9 v15:0x05ACEA v16:0x02ACEC v17:0x00ADEE]] atIndex:0];
[twitterView addSubview:[self label:self.twitterLabel forView:twitterView withName:#"Twitter" loggedIn:NO]];
[self.scrollView addSubview:twitterView];
}
This one does not show up, the layers specifically are off. However, here is the kicker, the label shows in the right spot because the labels frame is based on it's parent view frame.
-(UILabel *)label:(UILabel *)viewLabel forView:(UIView *)accountView withName:(NSString *)name loggedIn:(BOOL)loggedinStatus {
UILabel *label = viewLabel;
label.frame = CGRectMake(0, accountView.frame.size.height - 50, accountView.frame.size.width, 50);
label.text = [self setAccountLabelForName:name loggedIn:loggedinStatus];
label.textColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentLeft;
return label;
}
here is a picture that shows you that the label is based off the parents view frame, and it shows up correctly, but the gradient does not, and it's based off the same frame.
and my gradient method:
-(CAGradientLayer *)gradientLayerForViewFrame:(CGRect)viewFrame withColors:(NSArray *)colors {
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = viewFrame;
gradient.colors = colors;
return gradient;
}
For some reason when inserting my gradient layer to the views layer I had to change it:
//INSTEAD OF THIS:
[... insertSublayer:[self gradientLayerForViewFrame:facebookView.frame...];
//THIS WORKED FLAWLESSLY:
[... insertSublayer:[self gradientLayerForViewFrame:facebookView.bounds...];
I want to add a Label and an Image in titleView of my NavigationItem. I am adding UILabel and UIImageView to a UIView and setting it as titleView of the navigation Item. Things are being added, but I am not able to calculate the length of label and place image next to it.
My code is :-
// Title Name + Image
UIView *titView = [[UIView alloc] initWithFrame:self.navigationItem.titleView.bounds];
self.navigationItem.titleView = titView;
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(-10, -20, 150, 30)];
title.text = #"Bunny ";
[title setTextColor:[UIColor orangeColor]];
[titView addSubview:title];
float x2 = 30; //+ title.bounds.size.width;
UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"return" ]];
img.frame = CGRectMake(x2, -20, img.bounds.size.width, 30);
[titView addSubview:img];
I am looking for some way to calc the width text and set accordingly the width of the label. Right now I have set the width of the label as 150. And secondly, calc the x position to place the image just next to the label.
Tried many ways, but nothing works as expected. How can I achieve this ? Can you he give some guidelines such that regardless of length of text of label, things works as expected and UIView gets placed in the center of navigation item.
Any help is highly appreciated. Thanks.
You can call
[title sizeToFit];
after setting its properties and it will size itself to match the contained string.
Set the imageViews x origin to
CGRectGetMaxX(title.frame) + desiredSpacing;
And it could help to subclass UIView to achieve the final results by overwriting layoutSubviews and placing your views there, since the titleView's frame can be adjusted by the navigationBar...basically like this:
#implementation TitleView{
UILabel *_titleLabel;
UIImageView *_img;
}
- (id)initWithTitle:(NSString *)title andImage:(UIImage *)image
{
self = [super init];
if (self) {
_titleLabel = [[UILabel alloc] init];
_titleLabel.text = title;
[_titleLabel setTextColor:[UIColor orangeColor]];
[_titleLabel sizeToFit];
[self addSubview:_titleLabel];
_img = [[UIImageView alloc] initWithImage:image];
[self addSubview:_img];
}
return self;
}
- (void)layoutSubviews{
CGFloat spacingBetweenTextAndImage = 0;
CGFloat width = CGRectGetWidth(_titleLabel.frame)+CGRectGetWidth(_img.frame)+spacingBetweenTextAndImage;
CGFloat x = (CGRectGetWidth(self.bounds)-width)/2;
_titleLabel.frame = CGRectMake(x, (CGRectGetHeight(self.bounds)-CGRectGetHeight(_titleLabel.bounds))/2, CGRectGetWidth(_titleLabel.bounds), CGRectGetHeight(_titleLabel.bounds));
x+=CGRectGetWidth(_titleLabel.bounds)+spacingBetweenTextAndImage;
_img.frame = CGRectMake(x, (CGRectGetHeight(self.bounds)-CGRectGetHeight(_img.bounds))/2, CGRectGetWidth(_img.bounds), CGRectGetHeight(_img.bounds));
}
#end
use in your viewController:
UIView *titleView = [[TitleView alloc] initWithTitle:#"Bunny" andImage:[UIImage imageNamed:#"return" ]];
self.navigationItem.titleView = titleView;
I would like to use a UITextField to enter text into a UITextField instead of UIPickerView using the UITextField .tag
The view is quite complex and consists of several views which I will explain.
htmlContainerScrollView, contains multiple
- axisContainerScrollView, contains multiple
- itemField
UITableView - used to pass text into itemField
So with that in mind, this is how I set up my htmlContainerScrollView. I have added comments to explaine what I am trying to achive.
- (void) displayViews {
// add scrollview, This view is ued to hold all of the axis (vertical scrolling only)
htmlContainerScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 44.0, self.view.frame.size.width, 309.0)];
//TODO: replace this array with a dynamic implementation of the axis images. Will need someone to design the images for me
imagesArray = [NSArray arrayWithObjects:[UIImage imageNamed:#"LPA.png"], [UIImage imageNamed:#"LPB.png"], [UIImage imageNamed:#"LPC.png"], [UIImage imageNamed:#"LPD.png"], [UIImage imageNamed:#"LPA.png"], [UIImage imageNamed:#"LPB.png"], [UIImage imageNamed:#"LPC.png"], [UIImage imageNamed:#"LPD.png"], [UIImage imageNamed:#"LPA.png"], [UIImage imageNamed:#"LPB.png"], [UIImage imageNamed:#"LPC.png"], [UIImage imageNamed:#"LPD.png"], [UIImage imageNamed:#"LPA.png"], [UIImage imageNamed:#"LPB.png"], [UIImage imageNamed:#"LPC.png"], [UIImage imageNamed:#"LPD.png"], [UIImage imageNamed:#"LPA.png"], [UIImage imageNamed:#"LPB.png"], [UIImage imageNamed:#"LPC.png"], [UIImage imageNamed:#"LPD.png"], [UIImage imageNamed:#"LPA.png"], [UIImage imageNamed:#"LPB.png"], [UIImage imageNamed:#"LPC.png"], [UIImage imageNamed:#"LPD.png"], nil];
// Loop creates each axis
tagNumber = 1; // init the tagNumver starting from 1
for(int i = 0; i< axisNo; i++) {
CGFloat y = i * 77; // places each axis 77pxl below the previous
int itemsForRow = [itemsArray[i] intValue]; // get the current number of items for this axis
int scrollWidth = (itemsForRow * 40)+4; // calculate scroll width using the umber of items for this axis * by the size of each item.textfield
// create axis scroll view (horizontal scrolling only)
UIScrollView *axisContainerScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, y,self.view.frame.size.width, 77.0)]; //device view width etc.
axisContainerScrollView.contentSize = CGSizeMake(scrollWidth, 77.0); // axis.view scrollable width
axisContainerScrollView.backgroundColor = [UIColor whiteColor];
[htmlContainerScrollView addSubview:axisContainerScrollView];
// make sure the view goes right to the edge of the screen.
UIView *view = [[UIView alloc] init];
view.frame = CGRectMake(0.0, 0.0, scrollWidth+10, 77.0);
//grey header for each cell, if the total number of items exceeds the width of the device view then make the header the correct size
if(scrollWidth > self.view.frame.size.width) {
topBorder = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, scrollWidth, 18.0)];
topBorder.backgroundColor = [UIColor colorWithRed:colorController.fbRed/255.0 green:colorController.fbGreen/255.0 blue:colorController.fbBlue/255.0 alpha:1.0];
} else {
topBorder = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 18.0)];
topBorder.backgroundColor = [UIColor colorWithRed:colorController.fbRed/255.0 green:colorController.fbGreen/255.0 blue:colorController.fbBlue/255.0 alpha:1.0];
}
[axisContainerScrollView addSubview:topBorder];
[axisContainerScrollView addSubview:view];
int itemsCount = [itemsArray[i] intValue];
// add axis image to each scrollview (i.e. a, b, c, d, e, f, g etc.)
UIImageView *currentAxisImage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, y, 18.0, 18.0)];
currentAxisImage.image = imagesArray[i];
[htmlContainerScrollView insertSubview:currentAxisImage aboveSubview:view];
// loop creates each item for current axis
for (int i = 0; i < itemsCount; i++) {
// create header for itemField
itemHeaderLabel = [[UILabel alloc] initWithFrame:CGRectMake((i*40)+2, 20, 40, 15)];
itemHeaderLabel.backgroundColor = [UIColor colorWithRed:colorController.grRed/255.0 green:colorController.grGreen/255.0 blue:colorController.grBlue/255.0 alpha:1.0];
[itemHeaderLabel setTextAlignment:NSTextAlignmentCenter];
itemHeaderLabel.font = [UIFont fontWithName:#"Helvetica" size:14];
itemHeaderLabel.textColor = [UIColor whiteColor];
NSString *strFromInt = [NSString stringWithFormat:#"%d",i+1]; // start from 1 not 0
itemHeaderLabel.text = strFromInt;
[view addSubview:itemHeaderLabel];
// itemField is the UITextField I would like to add text too from UITableViewCell selections
itemField = [[UITextField alloc] initWithFrame:CGRectMake((i*40)+2, 35, 40, 40)];
itemField.delegate = self; // set delegate so you can use UITextField delegate methods
itemField.textColor = [UIColor blackColor];
[itemField setTextAlignment:NSTextAlignmentCenter];
itemField.font = [UIFont fontWithName:#"Helvetica" size:20];
itemField.backgroundColor=[UIColor whiteColor];
itemField.layer.borderColor = [[UIColor colorWithRed:colorController.grRed/255.0 green:colorController.grGreen/255.0 blue:colorController.grBlue/255.0 alpha:1.0] CGColor];
itemField.layer.borderWidth = 0.5f;
[view addSubview:itemField];
itemField.tag = tagNumber; // set tag
tagNumber ++;
[columnArrayOfTextFields addObject:itemField]; // array of items textfields.. not using this currently but might become usefull in the future. (legacey code)
}
[rowArrayOfTextFields addObject:columnArrayOfTextFields]; // array of arrays.. not using this currently but might become usefull in the future. (legacey code)
}
// exit loop, set first reasponder to the first itemField.
[itemField viewWithTag:1];
[itemField becomeFirstResponder];
// add the whole scrollview to the mainview.
htmlContainerScrollView.contentSize = CGSizeMake(self.view.frame.size.width, 77 *axisNo);
[self.view addSubview:htmlContainerScrollView];
}
So at this point I have created the view and assigned each itemField a unique tag value. Now I will show you my didSelectRowAtIndexPath which is not complete, I think this is where I should set the text using the UITextFieldDelegates but I am not sure how.
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
itemField.text = selectedCell.textLabel.text; // dose not work.. dosnt call UITextfield delegates or anything
[tableView deselectRowAtIndexPath:indexPath animated:YES]; //turns the UITableViewCell button as apposed to a single press fielf
}
and finally these are my UITextFieldDelegates.
- (void)textFieldDidBeginEditing:(UITextField *)textField {
itemField.text = textField.text;
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
return NO; // Hide keyboard so that you can use the UITableView selections to populate the UITextfeild itemField
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
currentSelected.text = textField.text;
NSInteger nextTag = currentSelected.tag + 1;
// Set next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// probably dont need this if I am not showing the UIkeyboard
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
You should create a custom tableview cell which has a uitextfield in it. This way you can easily set its delegate to self in cellForRowAtIndexPath like this:
- (UITableViewCell *)tableView:(UITableView *)view cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCellWithTextField* cell = .. //create cell
cell.textField.delegate = self;
return cell;
}
If you don't want to put it in tableview, fix this:
[itemField viewWithTag:1];
[itemField becomeFirstResponder];
should be:
itemField = [view viewWithTag:1];
[itemField becomeFirstResponder];
I wanna center vertically and horizontally an image inside of HeaderSection and a label inside of the image. But I don't have a clear idea about how make that. My code is:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIImage *image = [UIImage imageNamed:#"bg_title_category"];
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)] autorelease];
UILabel *sectionTitle = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)] autorelease];
UIImageView *sectionHeaderBG;
sectionTitle.text = #"Trial"; //[[tableDataSource objectAtIndex: section] objectForKey: #"Title"];
sectionTitle.textAlignment = NSTextAlignmentCenter;
sectionTitle.font = [UIFont fontWithName:#"Helvetica-Bold" size:14];
sectionTitle.textColor = [UIColor whiteColor];
sectionTitle.shadowColor = [UIColor colorWithWhite:0 alpha:0.4];
sectionTitle.shadowOffset = CGSizeMake(1, 1);
sectionTitle.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
sectionHeaderBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _tableView.frame.size.width/2, image.size.height)];
sectionHeaderBG.image = [UIImage imageNamed:#"bg_title_category"];
[headerView addSubview:sectionHeaderBG];
[headerView addSubview:sectionTitle];
return headerView;
}
But this code not center anything... Thanks in advance!
The problem is that you're creating headerView with origin (0,0) and it's size the same one as your image; then you're adding all of your views to headerView. When the table view adds this header view it will not be centered, rather it'll placed at (0,0).
What I'd suggest you to do is to create headerView with the same origin (0,0) but with the width of your tableView and the height depening on you. Let's just assume for now the height will be the same as your image plus 10px at the top and bottom just to give it some margin. Then you can add your UIImageView and UILabel inside headerView and center them with respect to it. It'd be something like this:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIImage *image = [UIImage imageNamed:#"bg_title_category"];
// Create your headerView with the same width as the tableView and a little taller than the image
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0, tableView.bounds.size.width, image.size.height + 20)]; //10px top and 10px bottom. Just for illustration purposes.
// Create the image view
UIImageView *sectionHeaderBG = [[UIImageView alloc] initWithImage:image];
// Now center it and add it to headerView
sectionHeaderBG.center = CGPointMake(headerView.bounds.size.width/2, headerView.bounds.size.height/2);
[headerView addSubview: [sectionHeaderBG autorelease]];
// Now it's turn of the label. Again I suggest using the tableView's width
UILabel *sectionTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
// Now center it. You could even do this when creating it's frame
sectionTitle.center = CGPointMake(headerView.bounds.size.width/2, headerView.bounds.size.height/2);
// do the rest of the configuration for your label...
// and add it to headerView
[headerView addSubview: [sectionTitle autorelease]];
return [headerView autorelease];
}
Hope this helps!