簡體   English   中英

如何從UIbutton選擇器調用方法?

[英]How do I call a method from a UIbutton selector?

我如何從下面的按鈕選擇器代碼中調用此方法:

- (void)displayEditorForImage:(UIImage *)imageToEdit

{

    AFPhotoEditorController *editorController = [[AFPhotoEditorController alloc] initWithImage:imageToEdit];

    [editorController setDelegate:self];

    [self presentViewController:editorController animated:YES completion:nil];

}

這是我正在嘗試使用以下方法調用的UIButton:

//edit button
UIButton *editButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[editButton addTarget:self
               action:@selector(editBtnTouch)
     forControlEvents:UIControlEventTouchDown];

[editButton setTitle:@"Effects" forState:UIControlStateNormal];


**// the following line shows the selector where I'm unsure how to call the method from the code above**
if ([[UIScreen mainScreen] respondsToSelector:@selector(displayEditorForImage:)] &&
        ([UIScreen mainScreen].scale == 2.0)) {
        // Retina display
        editButton.frame = CGRectMake(220.0, 320.0, 60.0, 40.0);


} else {
    editButton.frame = CGRectMake(220.0, 315.0, 60.0, 40.0);
}

[self.view addSubview:editButton];

謝謝您的幫助

調用添加到按鈕的選擇器時,如果選擇器允許,則按鈕本身將作為第一個參數傳遞。 為了獲得對圖像的引用,您可能需要執行以下操作(假設您想要的圖像是按鈕的背景圖像):

- (void)displayEditorForImage:(UIButton*)sender {
    UIImage* imageToEdit = [sender backgroundImageForState:UIControlStateNormal];
    AFPhotoEditorController *editorController = [[AFPhotoEditorController alloc] initWithImage:imageToEdit];

    [editorController setDelegate:self];

    [self presentViewController:editorController animated:YES completion:nil];
}

或者,您需要創建一個自定義UIButton,該UIButton具有關聯圖像的額外屬性,然后只需通過選擇器中的按鈕訪問該圖像:

- (void)displayEditorForImage:(UIButton*)sender {
    if([sender isKindOfClass:[YourCustomButtonClass class]]) {
        UIImage* imageToEdit = ((YourCustomButtonClass*)sender).customImageProperty;

        AFPhotoEditorController *editorController = [[AFPhotoEditorController alloc] initWithImage:imageToEdit];

        [editorController setDelegate:self];

        [self presentViewController:editorController animated:YES completion:nil];
    }
}

編輯:

您似乎對如何使UIButton在點擊時調用方法感到困惑。 您需要添加將方法定義為按鈕目標的對象(在本例中為self ),將方法添加為選擇器,並在點擊按鈕時使用UIControlEventTouchUpInside調用該方法。 因此您的代碼將是:

[editButton addTarget:self action:@selector(displayEditorForImage:) forControlEvents:UIControlEventTouchUpInside];

暫無
暫無

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

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