簡體   English   中英

Objective c / iOS:如何在 viewController 中覆蓋自定義類的 layoutSubviews

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

我創建了一個自定義 UILabel 類並設置了默認背景顏色。 這是我的自定義類的 .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 中設置標簽的 backgroundColor ,因此我認為滿足您需求的最佳方法是檢查標簽是否設置了 backgroundColor ,如果沒有則設置它。

/* 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;}

感謝@Meiliang Dong

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM