使用自定义tableview Cell中的按钮

时间:2012-10-08 09:13:09

标签: objective-c ios uitableview uibutton

我在自定义tableview单元格中有一个类似facebook的按钮。在我的tableview类中,我有以下功能。

- (IBAction)sendLike:(id)sender
          WithString: (NSString *)shareString
              andUrl:(NSURL *)shareUrl{

          //Do all kinds of things


        [fbController setInitialText:shareString];
        [fbController addURL:shareUrl];
        [fbController setCompletionHandler:completionHandler];
        [self presentViewController:fbController animated:YES completion:nil];
    }
}

在我的cellForRowAtIndexpath中,我试图以下列方式调用此方法。

 NSString *shareString = video.name;
        NSURL *shareUrl = [NSURL URLWithString:video.url];
        [cell.facebook addTarget:self action:@selector(sendLike: WithString:shareString andUrl:shareUrl)
                 forControlEvents:UIControlEventTouchUpInside];

但它抱怨我应该在我的@selector中添加':'。有人可以帮忙吗?

提前致谢。

5 个答案:

答案 0 :(得分:1)

您可以尝试这样

cell.facebook.tag = indexPath.row.
    [cell.facebook addTarget:self action:@selector(sendLike:)
                     forControlEvents:UIControlEventTouchUpInside];

在sendLike事件中

- (IBAction)sendLike:(id)sender
  {


        //if you want to fetch data from any list then try
        //UIButton *selectedButton = (UIButton*)sender;
        //data = [dataList objectAtIndex:selectedButton.tag];
        NSString *shareString = video.name;
        NSURL *shareUrl = [NSURL URLWithString:video.url];

        [fbController setInitialText:shareString];
        [fbController addURL:shareUrl];
        [fbController setCompletionHandler:completionHandler];
        [self presentViewController:fbController animated:YES completion:nil];
    }

答案 1 :(得分:0)

正如Apple文档中所述,操作中@selector的唯一可用规范是以下方法:

- (void)action;

- (void)action:(id)sender;

- (void)action:(id)sender forEvent:(UIEvent *)event;

正如您所看到的,您的选择器与此不匹配,因为您有多个参数,但只允许发件人id

作为解决方案,您可以为按钮设置tag,然后在选择器中处理它。

答案 2 :(得分:0)

cellForRow中: //将自定义字符串连接到按钮

objc_setAssociatedObject(yourButton, "theKey", strText, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

在你的按钮处理程序中:

NSString *str = objc_getAssociatedObject(sender, "theKey");

p.s不要忘记导入运行时库: #import <objc/runtime.h>

答案 3 :(得分:0)

我认为你以错误的方式调用了选择器。你真的应该写,

[cell.facebook addTarget:self action:@selector(sendLike: WithString: andUrl:)  
                                     forControlEvents:UIControlEventTouchUpInside];  

但这不会为你传递论据。如果你想传递参数,你应该调用 performSelector ,如

[self performSelector:@selector(sendLike: WithString: andUrl:) 
                                withObject: cell.facebook
                                withObject: shareString
                                withObject: shareUrl]; 

希望它有助于解决您的问题。

答案 4 :(得分:0)

您的问题是选择器中参数的数量和种类不正确。您只能使用具有以下方案的目标:

 - (void)action;
 - (void)action:(id)sender;
 - (void)action:(id)sender forEvent:(UIEvent *)event;

您必须在发件人(UITableViewCell类实例)对象中包含您的信息。您可以按照Stas的其他答案中的描述执行此操作,但我建议您创建一个自定义表视图单元子类,该子类为shareStringshareURL添加属性。这种方法需要更多的代码,但是更容易读取,维护并防止这种丑陋的Obj-C和C混淆。

相关问题