设置UILabel文本无效

时间:2014-08-01 20:45:42

标签: ios objective-c uilabel iboutlet

这是我的.h文件

#import <UIKit/UIKit.h>

@interface PersonViewController : UIViewController

@property(strong,nonatomic) NSString *personTitle;

这是我的.m文件

@interface PersonViewController ()

@property (weak, nonatomic) IBOutlet UILabel *titleView;

@end

@implementation PersonViewController
//stuff …

-(void)setPersonTitle:(NSString *)personTitle
{
    [self.titleView setText:personTitle];// also self.titleView.text=personTitle
    [self.titleView setNeedsDisplay];
    NSLog(@"The title shoud match as %@ :: %@",personTitle,self.titleView.text);
}

-(NSString *)personTitle
{
    return self.titleView.text;
}

//… more stuff

@end

日志记录显示(null)的值为self.titleView.text,而personTitle会打印相应的值。

我记得曾多次做过同样的事情并且有效。任何想法为什么这次失败?

更新我使用故事板设置我的场景。我正在使用xcode-5和iOS-7

更新:我如何致电

用户单击按钮,导致推送segue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSLog(@"enter prepare for segue.");
    NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];

 if ([segue.identifier isEqualToString:the_identifier_for_person]) {
        NSLog(@"segue to person is progressing“);
        if ([segue.destinationViewController isKindOfClass:[PersonViewController class]]) {
            NSLog(@"segue to person destination is a match");

            PersonViewController *aPerson = (PersonViewController *)segue.destinationViewController;
            aPerson.personTitle=((MyItem*)self.allItems[indexPath.row]).title;
            NSLog(@"segue to person is done");

        }
    }
}

4 个答案:

答案 0 :(得分:1)

这听起来好像忘了在故事板中连接UILabel。你能确认self.titleView不是空的吗?

答案 1 :(得分:1)

视图控制器根据需要创建视图,但只能通过调用view来发现它们。加载视图后,将填充您的插座。

调用view强行加载或暂停字符串,直到获得viewDidLoad

(除了:在iOS 6之前,视图也会在内存不足的情况下发布,因此惯用的事情是存储字符串并填充在viewDidLoad上)

答案 2 :(得分:1)

接受了另一个答案,我想展示我实际用来解决问题的模式,以防其他人来看。这种模式是最好的做法(是的,我在那里忘了很久)。

#pragma mark - update UI
-(void)setPersonTitle:(NSString *)personTitle
{
    _personTitle=personTitle;
    if (self.view.window) [self updateUI];//only if I am on screen; or defer to viewWillAppear
}
-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self updateUI];
}
-(void)updateUI
{
    self.titleView.text=self.personTitle;
}

在数据发生变化时更新ui总是很重要,这就是我必须在setPersonTitle内进行调用的原因。但是因为我在prepareForSegue中设置personTitle时尚未设置IBOutlets,所以我还必须在viewWillAppear内进行调用。

答案 3 :(得分:0)

您实际上是在调用-(void)setPersonTitle:(NSString *)personTitle方法吗?

您似乎没有正确调用它会导致标题为空。

在查看prepareForSeque之后,很明显您没有调用该方法。您实际上只是更改名为personTitle的@property

在viewDidLoad中你应该拥有self.titleView.text = self.personTitle;