質問
私は
例えば、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 ..
}
//...
}
UPDATE:sender.tagはNSInteger
代わりにNSInteger *
なければならない
あなたは<のhref = "https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocAssociativeReferences.html#//apple_ref/doc/uid/TP30001163-を使用することができますCH24-SW3" のrel = "noreferrer">連想参照が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の答えからタグよりも直接的であることがわかり変数を渡すための別のオプションは、accessibilityHint内の文字列を渡すことです。たとえばます:
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
}
}
あなたが使用することをdot'n 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]);
}