这是我的TableHeaderView
课程,其范围为UITableViewHeaderFooterView
。这个类没有Nib文件,一切都是以编程方式完成的。
我希望它的背景颜色是透明的,但我不能让它工作。
我已尝试设置[self.backgroundView setBackgroundColor:[UIColor clearColor]]
,[self setBackgroundView:nil]
,[self.contentView setBackgroundColor:[UIColor clearColor]]
,但最终结果始终为黑色背景。
我已经花了好几个小时,我真的不知道如何解决这个问题。我需要做些什么来实现这个目标?
#import "TableHeaderView.h"
@interface TableHeaderView ()
@property (strong, nonatomic) UIView *background;
@property (strong, nonatomic) UILabel *text;
@end
@implementation TableHeaderView
- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithReuseIdentifier:reuseIdentifier];
if (self.contentView) {
self.background = [UIView new];
[self.background setBackgroundColor:[UIColor colorWithWhite:0.0f alpha:0.5f]];
[self.background setTranslatesAutoresizingMaskIntoConstraints:NO];
self.text = [UILabel new];
[self.text setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.text setText:@"Label"];
[self.text setFont:[UIFont fontWithName:@"HelveticaNeue" size:15.0f]];
[self.text setTextColor:[UIColor whiteColor]];
[self.text setBackgroundColor:[UIColor redColor]];
[self.background addSubview:self.text];
[self.contentView addSubview:self.background];
[self.contentView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.background addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[L]-10-|"
options:0
metrics:nil
views:@{@"L": self.text}]];
[self.background addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[L]|"
options:0
metrics:nil
views:@{@"L": self.text}]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[V]-10-|"
options:0
metrics:nil
views:@{@"V": self.background}]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[V]|"
options:0
metrics:nil
views:@{@"V": self.background}]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[contentView]|"
options:0
metrics:nil
views:@{@"contentView" : self.contentView}]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[contentView]|"
options:0
metrics:nil
views:@{@"contentView" : self.contentView}]];
[self setBackgroundView:[UIView new]]; // I can't change this background color to
[self.backgroundView setBackgroundColor:[UIColor whiteColor]]; // be transparent. It gets black instead.
}
return self;
}
@end
更新
我尝试使用Nib文件并使用此初始化程序:
- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithReuseIdentifier:reuseIdentifier];
if (self) {
[self.contentView addSubview:[[[NSBundle mainBundle] loadNibNamed:@"TableHeaderView" owner:self options:nil] firstObject]];
}
return self;
}
Nib文件像旧代码一样设置视图。但它仍然无法运作,我无法获得透明背景。
更新2
问题在于我还覆盖了drawRect:
,这样做会导致黑色背景。将其中的代码移动到另一个方法可以解决问题。