문제

예를 들어 UIButton 작업에 변수를 전달하고 싶습니다.

NSString *string=@"one";
[downbutton addTarget:self action:@selector(action1:string)
     forControlEvents:UIControlEventTouchUpInside];

내 작업 기능은 다음과 같습니다.

-(void) action1:(NSString *)string{
}

그러나 구문 오류를 반환합니다.UIButton 작업에 변수를 전달하는 방법은 무엇입니까?

도움이 되었습니까?

해결책

읽기로 변경하십시오.

[downbutton addTarget:self action:@selector(action1:) forControlEvents:UIControlEventTouchUpInside];

iPhone SDK에 대해 잘 모르지만 버튼 작업의 대상은 아마도 ID (보통 발신자라는 이름)를받을 수 있습니다.

- (void) buttonPress:(id)sender;

메소드 호출 내에서 발신자는 귀하의 경우 버튼이어야하므로 이름, 태그 등과 같은 속성을 읽을 수 있습니다.

다른 팁

여러 버튼을 구별해야 하는 경우 다음과 같은 태그로 버튼을 표시할 수 있습니다.

[downbutton addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
downButton.tag = 15;

작업 대리자 메서드에서는 이전에 설정된 태그에 따라 각 버튼을 처리할 수 있습니다.

(void) buttonPress:(id)sender {
    NSInteger tid = ((UIControl *) sender).tag;
    if (tid == 15) {
        // deal with downButton event here ..
    }
    //...
}

업데이트:sender.tag는 다음과 같아야 합니다. NSInteger 대신에 NSInteger *

당신이 사용할 수있는 연관 참조 Uibutton에 임의의 데이터를 추가하려면 :

static char myDataKey;
...
UIButton *myButton = ...
NSString *myData = @"This could be any object type";
objc_setAssociatedObject (myButton, &myDataKey, myData, 
  OBJC_ASSOCIATION_RETAIN);

정책 필드 (OBJC_ASSOCIATION_RETAIN)의 경우 귀하의 사례에 적합한 정책을 지정하십시오. 행동 대의원 방법에 대해 :

(void) buttonPress:(id)sender {
  NSString *myData =
    (NSString *)objc_getAssociatedObject(sender, &myDataKey);
  ...
}

Leviatan의 답변에서 태그보다 직접적으로 찾는 변수를 전달하기위한 또 다른 옵션은 접근성에 문자열을 전달하는 것입니다. 예를 들어:

button.accessibilityHint = [user objectId];

그런 다음 버튼의 동작 방법에서 :

-(void) someAction:(id) sender {
    UIButton *temp = (UIButton*) sender;
    NSString *variable = temp.accessibilityHint;
    // anything you want to do with this variable
}

내가이 작업을 수행하는 유일한 방법은 작업을 호출하기 전에 인스턴스 변수를 설정하는 것입니다.

Uibutton을 확장하고 사용자 정의 속성을 추가 할 수 있습니다

//UIButtonDictionary.h
#import <UIKit/UIKit.h>

@interface UIButtonDictionary : UIButton

@property(nonatomic, strong) NSMutableDictionary* attributes;

@end

//UIButtonDictionary.m
#import "UIButtonDictionary.h"

@implementation UIButtonDictionary
@synthesize attributes;

@end

버튼의 태그를 설정하고 실제로 발신자로부터 액세스 할 수 있습니다.

[btnHome addTarget:self action:@selector(btnMenuClicked:)     forControlEvents:UIControlEventTouchUpInside];
                    btnHome.userInteractionEnabled = YES;
                    btnHome.tag = 123;

호출 된 함수에서

-(void)btnMenuClicked:(id)sender
{
[sender tag];

    if ([sender tag] == 123) {
        // Do Anything
    }
}

당신은 당신이 사용하는 uicontrolstates의 문자열을 사용할 수 있습니다.

NSString *string=@"one";
[downbutton setTitle:string forState:UIControlStateApplication];
[downbutton addTarget:self action:@selector(action1:) forControlEvents:UIControlEventTouchUpInside];

그리고 행동 함수 :

-(void)action1:(UIButton*)sender{
    NSLog(@"My string: %@",[sender titleForState:UIControlStateApplication]);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top