簡體   English   中英

IBAction在第二個View Controller中設置UIImageview圖像?

[英]IBAction to set UIImageview image in second View Controller?

我正在嘗試設置一些內容,其中來自view controller 1IBAction將使用標簽來區分所按下的按鈕,從而在View Controller 2's viewDidLoad設置ImageView圖像。...類似(不是精確的代碼...只是將其散列在其中我的頭):

在View Controller 1中:

-(IBAction)buttonpressed:(id)sender {

if (button.tag == 1) {

ViewController2ImageView.image = [UIImage imageNamed:@"image1.png"];

}else if (button.tag == 2) {

ViewController2ImageView.image = [UIImage imageNamed:@"image2.png"];
}

在View Controller 2中:

-(void)viewDidLoad {

ViewController2ImageView.image = [UIImage imageNamed:@"?.png"];
}

問題是如何從IBAction獲取信息以傳遞給第二個視圖控制器,並讓viewDidLoad方法加載正確的圖像。

我見過一些將數據轉換為NSString並以這種方式傳遞的示例,但是我真的想知道是否有更好的方法可以解決此問題。

到目前為止,我已經能夠通過將一些應用程序整合到Google中來,但是這已經讓我撓頭了幾天。

任何幫助或建議的代碼都會有所幫助! 即使只是朝正確方向推動。

謝謝!

在viewController1中按下按鈕時,請執行以下操作:

-(IBAction)buttonpressed:(id)sender {
    if (button.tag == 1) {
        [[NSUserDefaults standardUserDefaults] setObject:@"image1.png" 
            forKey:@"viewController2SelectedImageKey"];
    } else if (button.tag == 2) {
        [[NSUserDefaults standardUserDefaults] setObject:@"image2.png" 
            forKey:@"viewController2SelectedImageKey"];
    } else {
        //set some default string for the image
        [[NSUserDefaults standardUserDefaults] setObject:@"yourDefaultImage.png" 
            forKey:@"viewController2SelectedImageKey"];
    }
}

然后在viewController2的viewDidLoad方法中執行以下操作

- (void)viewDidLoad {
    ViewController2ImageView.image = [UIImage imageNamed:[[NSUserDefaults 
        standardUserDefaults] objectForKey:@"viewController2SelectedImageKey"]];
    //other setup
}

這段代碼將字符串設置為NSUserDefaults plist中的鍵(我使用的鍵是@“ viewController2SelectedImageKey”,但您可以使用任何喜歡的字符串),它由viewController2的viewDidLoad方法引用,並使用該字符串作為圖像文件。

為什么不使用NSString *imageName屬性將文件名傳遞給View Controller 2?

您好,您可以簡單地使用以下類型進行多種操作:1)您可以編寫方法

  • (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle )nibBundleOrNil andImageName:(NSString )ImageName;

    在第二個視圖中寫入此方法,然后從第一個視圖中調用,然后在該方法調用時將該圖像名稱存儲在第二個本地變量中,如下所示

    • (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle )nibBundleOrNil andImageName:(NSString )ImageName {self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if(self){//自定義初始化//局部變量分配imageName = ImageName; 自我回報; }

然后在您的代碼中傳遞它

  • (void)viewDidLoad {ViewController2ImageView.image = [UIImage imageNamed:imageName]; }

2)第二種類型是在secound視圖中創建imageName Varibale並提供@property和@synthesize,然后在下面使用它

 SecoundView *ObjSecoundView=[[ObjSecoundView alloc] initWithNibName:@"SecoundView" bundle:nil];
    ObjSecoundView.imageName=@"Image1.png";//put ur dynamic image name
    [self.navigationController  pushViewController:ObjSecoundView animated:YES];

通過此並在viewdid加載方法中使用,如下所示

  • (void)viewDidLoad {ViewController2ImageView.image = [UIImage imageNamed:imageName]; }

暫無
暫無

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

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