objective-c 无法在 UILabel 上设置文本字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/259471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:53:16  来源:igfitidea点击:

Unable to set text field on UILabel

objective-ccocoa-touchuilabel

提问by lucasweb

I have created UITableCellViewclass called NoteCell. The header defines the following:

我创建了一个UITableCellView名为NoteCell. 标题定义了以下内容:

#import <UIKit/UIKit.h>
#import "Note.h"

@interface NoteCell : UITableViewCell {
    Note *note;
    UILabel *noteTextLabel;  
}

@property (nonatomic, retain) UILabel *noteTextLabel;

- (Note *)note;
- (void)setNote:(Note *)newNote; 

@end

In the implementation I have the following code for the setNote:method:

在实现中,我有以下setNote:方法代码:

- (void)setNote:(Note *)newNote {
    note = newNote;
    NSLog(@"Text Value of Note = %@", newNote.noteText);
    self.noteTextLabel.text = newNote.noteText;
    NSLog(@"Text Value of Note Text Label = %@", self.noteTextLabel.text);
    [self setNeedsDisplay];
}

This fails to set the text field of the UILabeland the output of the log messages is:

这无法设置 的文本字段,UILabel并且日志消息的输出是:

2008-11-03 18:09:05.611 VisualNotes[5959:20b] Text Value of Note = Test Note 1  
2008-11-03 18:09:05.619 VisualNotes[5959:20b] Text Value of Note Text Label = (null)

I have also tried to set the text field of UILabelusing the following syntax:

我还尝试UILabel使用以下语法设置文本字段:

[self.noteTextLabel setText:newNote.noteText];

This does not seem to make a difference.

这似乎没有什么区别。

Any help would be much appreciated.

任何帮助将非常感激。

回答by Ben Gottlieb

Have you set up your noteTextLabel anywhere? What this looks like to me is that you're messaging a nil object. When you cell is created, noteTextLabel is nil. If you never set it up, you're basically doing the following:

你有没有在任何地方设置过你的 noteTextLabel?在我看来,您正在向一个 nil 对象发送消息。创建单元格时,noteTextLabel 为零。如果您从未设置过它,那么您基本上是在执行以下操作:

[nil setText: newNote.noteText];

And when you later try to access it, you're doing this:

当您稍后尝试访问它时,您正在这样做:

[nil text];

Which will return nil.

这将返回零。

In your -initWithFrame:reuseIdentifier:method, you need to explicitly create your noteTextLabel, and add it as a subview to your cell's content view:

在您的-initWithFrame:reuseIdentifier:方法中,您需要明确创建您的 noteTextLabel,并将其作为子视图添加到您单元格的内容视图中:

self.noteTextLabel = [[[UILabel alloc] initWithFrame: CGRectMake(0, 0, 200, 20)] autorelease];
[self.contentView addSubview: self.noteTextLabel];

Then this should work.

那么这应该有效。

Also, as a stylistic note, I would make the propertyfor noteTextLabel readonly, since you're only going to want to access it from outside the class, never set it.

此外,作为文体说明,我会将propertyfor noteTextLabel 设为只读,因为您只想从课程外部访问它,而不要设置它。