I created a Category on UIView with a method who’s purpose it to create and return a UIView object. It runs without errors but returns an empty UIView. Here’s the code:
#import <UIKit/UIKit.h>
@interface UIView (makeTableHeader)
-(UIView *) makeTableHeader:(NSString *)ImageName
withTitle:(NSString *)headerTitle
usingFont:(NSString *)fontName
andFontSize:(CGFloat)fontSize;
@end
Here’s the Implementation:
-(UIView *) makeTableHeader: (NSString *)ImageName
withTitle:(NSString *)headerTitle
usingFont:(NSString *)fontName
andFontSize:(CGFloat)fontSize {
// Create a master-view:
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 34)];
// Create the Image:
UIImageView *headerImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:ImageName]];
headerImageView.frame = CGRectMake(0, 0, 320, 34);
// Now create the Header LABEL:
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 320, 34)];
headerLabel.text = headerTitle;
headerLabel.font = [UIFont fontWithName:fontName size:fontSize];
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.textColor = [UIColor whiteColor];
headerLabel.shadowColor = [UIColor blackColor];
headerLabel.shadowOffset = CGSizeMake(1.0, 1.0);
// Finally add both both Header and Label as subview to the main Header-view:
[headerView addSubview:headerImageView];
[headerView addSubview:headerLabel];
return headerView;
}
Now here’s how I call this category-method:
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *hView = [[UIView alloc] init];
[hView makeTableHeader:@"redGradientHeader5@2x.jpg"
withTitle:@"Test Banner"
usingFont:@"boldSystemFont"
andFontSize:18];
return hView;
}
The code runs fine – but I get an empty view. Interestingly it does size the view correctly – giving it the CGRect coordinates I asked for – but there’s no image or label inside the view.
Anyone see what’s wrong?
You need to make the method a
classmethod, and assign it like this:You are making two views – one with alloc/init, and one with your custom function. However, you are only ever assigning the first one to
hView. This is because in themakeTableHeadermethod, you are usinghViewto create a second UIView, and applying the subviews/modifications to that rather than modifyinghView. This view is then returned by the method, and then immediately discarded because it is not assigned to anything.Alternatively, if you insist on keeping it an instance method and modifying the view, you’ll just have to do it like this (although I strongly do not suggest it):