我注意到我无法更新NSTextField上的文字:
mainClass.h
@property(strong, nonatomic) NSTextField *titleLabel;
mainClass.m
-(void)viewDidLoad {
LabelClass *element = [[LabelClass alloc] init];
[self.view addSubview:[element label:self.titleLabel title:@"My label" xCoord:0 yCoord:0 width:100 height:50]];
}
现在,如果尝试更新NSTextField文本,则不起作用:
mainClass.m
-(void)someMethod{
[self.titleLabel setStringValue:@"Updated text"];
}
我认为重要的是要注意'self.titleLabel'属性是在我尝试更新标签'mainClass.m'的当前类中创建的。我从'LabelClass.m'调用我的标签的类只包含创建标签的方法,所以我只创建了该类的实例,创建了标签并设置了'self.titleLabel':
LabelClass.m
@implementation LabelClass
-(NSTextField *)label:(NSTextField *)label title:(NSString *)title xCoord:(CGFloat)x yCoord:(CGFloat)y width:(CGFloat)width height:(CGFloat)height{
NSTextField *textField = [[NSTextField alloc] initWithFrame:CGRectMake(x, y, width, height)];
[textField setStringValue:title];
[textField setAlignment:NSCenterTextAlignment];
[textField setEditable:NO];
[textField setDrawsBackground:NO];
[textField setSelectable:NO];
[textField setBezeled:NO];
return textField;
}
答案 0 :(得分:1)
你的问题在这里:
-(void)viewDidLoad {
LabelClass *element = [[LabelClass alloc] init];
[self.view addSubview:[element label:self.titleLabel title:@"My label" xCoord:0 yCoord:0 width:100 height:50]];
}
您正在通过NSTextField
来电回复LabelClass
,但您永远不会将其分配给self.titleLabel
。试试这个:
-(void)viewDidLoad {
LabelClass *element = [[LabelClass alloc] init];
self.titleLabel = [element labelWithTitle:@"My Label" xCoord:0 yCoord:0 width:100 height:50];
[self.view addSubview:self.titleLabel];
}
然后修改你的label:title:xCoord:yCoord:width:height:
方法以删除label参数,因为你没有传入一个,你将返回一个。
-(NSTextField *)labelWithTitle:(NSString *)title xCoord:(CGFloat)x yCoord:(CGFloat)y width:(CGFloat)width height:(CGFloat)height{
NSTextField *textField = [[NSTextField alloc] initWithFrame:CGRectMake(x, y, width, height)];
[textField setStringValue:title];
[textField setAlignment:NSCenterTextAlignment];
[textField setEditable:NO];
[textField setDrawsBackground:NO];
[textField setSelectable:NO];
[textField setBezeled:NO];
return textField;
}