簡體   English   中英

從UITableView中更改要推送到的視圖中的UILabel

[英]Changing the UILabel in a view I'm pushing to, from a UITableView

我有一個名為“ FirstViewController”的表視圖,當我選擇表中的任何一個單元格時,它將推送到“ SecondViewController”。 SecondViewController有一個名為“ randomTitle”的UILabel,我需要根據FirstViewController上的選定單元格進行更改。

因此,如果選定的單元格命名為“隨機行”,則需要將UILabel更改為該行。

到目前為止,我還沒有嘗試過。 這放在FirstViewController中:

SecondViewController *secondView = [[SecondViewController alloc] init];
secondView.randomTitle.text = @"Test"; // hardcoding it for now

[self.navigationController pushViewController:secondView animated:YES];

但是標簽不會改變。 我想念什么? 筆尖已正確連接。 這是SecondViewController的.h樣子:

@interface SecondViewController : UIViewController
{
    UILabel *randomTitle;
}

@property (nonatomic, retain) IBOutlet UILabel *randomTitle;

恭喜,您遇到了導致此類怪胎的bug,這就是所謂的“您可以毫無問題地調用nil上的任何方法”。

當您將文本設置為標簽時,尚未將其設置為出口(因為控制器尚未開始加載其視圖;在按下按鈕后便會立即執行)。

為了保持您的代碼干凈和可維護,我建議創建一個屬性來保存文本(或者更好的是,與所選行關聯的模型),並在第二個控制器的viewWillAppear中使用它來配置其表示形式。

附言:為證明我是對的,只需在推送后放置文本即可

似乎在您希望設置其text屬性時,標簽尚未正確初始化。 將以下代碼添加到SecondViewController的init方法中:

randomTitle = [[UILabel alloc] init];

假設它已正確插入IB中,randomTitle標簽將具有您在IB中設置的所有屬性。 無論如何,您都需要像在FirstViewController方法中一樣,在設置標簽文本之前顯式分配標簽alloc-init

注意:我知道使用情節提要/ segues的工作原理,但是對於無segue的推送視圖,以下應適用於Second View Controller,但必須對First View Controller進行一些調整

NSString使用(nonatomic, copy)屬性。

在Second View Controller的.h文件中,創建一個NSString充當“傳輸字符串”

@property (nonatomic, copy) NSString *transferString;

在您的第二個View Controller的.m文件中,進行合成和取消分配等操作,並在viewDidLoad中:

-(void)viewDidLoad
{
    [super viewDidLoad];

    randomTitle.text = transferString;
}

這將根據輸入顯示您想要的特定文本。 現在要傳遞文本,您需要轉到First View Controller。 所有這些都在.m文件中進行。 首先,導入第二個View Controller:

#import "SecondViewController.h"

對於您的Segue:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"SegueName"]) 
    {        
        [[segue destinationViewController] setTransferString:[NSString stringWithFormat:@"%@", [yourArray objectAtIndex:yourTableView.indexPathForSelectedRow.row]]];
    }
}

其中yourArray是用於填充yourTableView的NSArray

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM