【问题标题】:UIButton with NSInvocation带有 NSInvocation 的 UIButton
【发布时间】:2010-09-13 07:18:25
【问题描述】:

我试图以编程方式添加一个按钮,按下它时,某个对象正在被传递。我不断收到“发送无法识别的选择器”异常。你能建议代码有什么问题吗:

    // allocate the details button's action
    SEL selector = @selector(showPropertyDetails:forProperty:);
    NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    [invocation setSelector:selector];
    //The invocation object must retain its arguments
    [property retain];      
    //Set the arguments
    [invocation setTarget:self];
    [invocation setArgument:&property atIndex:3];       
    [(UIButton*)[myView viewWithTag:15] addTarget:self action:@selector(selector) forControlEvents:UIControlEventTouchDown];

再往下看,同一个类中的方法如下:

-(void) showPropertyDetails:(id)something forProperty:(Property *)property {
int i=0;
}

【问题讨论】:

    标签: objective-c uibutton nsinvocation


    【解决方案1】:

    当您构建NSInvocation 时,您并没有在任何地方使用它——您只是将selector 设置为按钮的action。该选择器的格式应该类似于- (void)foo:(id)sender, ...

    您可以改为使用字典,例如标签作为映射到某个NSInvocation 或存储附加参数的键。

    【讨论】:

    • 所以您的意思是在单击按钮时发送多个参数的唯一方法是使用集合对象(字典、数组等),因为它们总是只接受一个参数?
    • @Amarsh:我的意思是你不能在这里使用 incovations 等,而是必须将信息和与按钮的关系存储在其他地方。
    • @George:是的,谢谢。您的评论确实帮助我解决了我的问题。谢谢。
    【解决方案2】:

    我以不同的方式解决了它。子类化 UIButton 并添加了我需要的所有属性。类是这样的:

    @interface RecentSalePropertyDetailsButton : UIButton {
        Property* property;
    }
    @property (nonatomic, retain) Property* property;
    @end
    @implementation RecentSalePropertyDetailsButton
    @synthesize property;
    - (id) initWithPropertyAs:(Property*)aProperty{
        [super init];
        self.property = aProperty;
        return self;
    }
    @end
    

    然后,再往下,我执行以下操作:

        // allocate the details button's action
        RecentSalePropertyDetailsButton* button = (RecentSalePropertyDetailsButton *)[myView viewWithTag:15];
        button.property = property;
        [button addTarget:self action:@selector(showRecentSalesPropertyDetails:) forControlEvents:UIControlEventTouchDown];
    

    【讨论】:

      【解决方案3】:
      //make a button
          UIButton *button = [UIButton buttonWithType:0];
      //set button size
          button.frame = CGRectMake(20,219,280,106);
      //give it a color
          button.backgroundColor = [UIColor clearColor];
      //add a method
          [button addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
      //add it to the currentview 
          [self.view addSubview:button];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-06
        • 2017-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多