Objective c / iOS:如何在 viewController 中覆盖自定义 class 的布局子视图

Objective c / iOS: How to override custom class's layoutSubviews in viewController

我创建了自定义 UILabel class 并设置了默认背景颜色。 这是我的自定义 class.

的 .h 和 .m 文件
#import <UIKit/UIKit.h>

@interface imLabel : UILabel

@end

#import "imLabel.h"

@implementation imLabel

- (void)drawRect:(CGRect)rect {
}

- (void) layoutSubviews {

self.backgroundColor = [UIColor redColor];

}

@end

它工作正常,但这是我需要的:只有在 ViewController 中未设置 backgroundColor 时我才希望这项工作。

这是我的viewDidLoad

- (void)viewDidLoad {
  [super viewDidLoad];

label = [[imLabel alloc] initWithFrame:CGRectMake(50, 50, 300, 300)];
label.backgroundColor = [UIColor blueColor];

[self.view addSubview:label];
}

您可以在 ViewController 中控制是否设置标签的背景颜色,所以我认为满足您需求的最佳方法是检查标签是否设置了背景颜色,如果没有设置它。

/* Somewhere in your ViewController */
if (!self.label.backgroundColor) {
    self.label.backgroundColor = [UIColor redColor];
}

删除 imLabel.m 中的所有其他代码,然后:-

  (instancetype)initWithFrame:(CGRect)aRect { self = [super initWithFrame:aRect]; if (self) { self.backgroundColor = [UIColor redColor]; } return self;}

感谢@董美良