![](/img/trans.png)
[英]ios - how to call ViewController.swift class from objective-c
[英]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.