我正在创建一个简单的代码,允许我在 UISwitcher 之外实例化 UILabel。 正在正常创建切换器,我创建了一个“UIRadio”类以在开始时正确实例化标签。
继承人.m:
#import "UIRadio.h"
@implementation UIRadio
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
-(id)initWithLabel:(CGRect)frame Label:(NSString*)labelText
{
self = [super init];
if (self) {
self.frame=frame;
label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 100)];
label.text=labelText;
[self.superview addSubview:label];
}
return self;
}
-(void)removeFromSuperview{
[label removeFromSuperview];
}
@end
这是 .h:
#import <UIKit/UIKit.h>
@interface UIRadio : UISwitch{
UILabel *label;
}
- (id)initWithLabel:(CGRect)frame Label:(NSString*)label;
@end
UILabel 似乎已正确创建,但未显示在 View 中。 有什么线索吗?
谢谢
最佳答案
我敢打赌,当您在 initWithLabel
方法中调用 addSubview
时,self.superview
为 nil。
我认为您将很难以这种方式添加标签。问题是,当您实例化 UIRadio
并使用 initWithLabel:Label:
初始化它时(顺便说一句,这是一个非常奇怪的签名,您是说 initWithFrame :label:
?) UIRadio
的实例还没有父 View 。正如您所说,您创建了标签,但还没有 super View ,因此您尝试将该标签添加到 View 层次结构的尝试失败了。
我建议您创建一个单独的 UIView
子类,它将包含 UISwitch
和标签。然后你可以实例化那个类,它的 init 方法可以创建一个开关和一个标签,并将这些控件作为 subview 添加到它自己。你可以尝试这样的事情:
@interface LabeledSwitch : UIView
@end
@implementation LabeledSwitch {
UISwitch *_switch;
UILabel *_label;
}
- (id)initWithFrame:(CGRect)frame labelText:(NSString *)labelText {
self = [super initWithFrame:frame];
if (self) {
_switch = [[UISwitch alloc] initWithFrame:CGRectZero];
_label = [[UILabel alloc] initWithFrame:CGRectZero];
_label.text = labelText;
[self addSubview:_switch];
[self addSubview:_label];
}
return self;
}
- (void)layoutSubviews {
// Whatever code you like to set reasonable frames
// for _switch and _label based on the current bounds
// of this container view.
}
@end
关于ios - 在实例化 UISwitcher 时尝试实例化 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24796837/