在UITableViewCell中将UIViewController设置为自定义UIView的委托

时间:2015-11-17 20:30:10

标签: objective-c uitableview uiviewcontroller delegates

所以标题几乎解释了我的问题。

我有UIViewController,其中包含UITableView。在所有UITableViewCells中都有自定义UIButton,但只有一个,我想将delegate设置为顶级{{1} }}。即点击此按钮,会触发UIViewController

上发生的事情

如果我在所有按钮上设置UIViewController,这可以正常工作 - 但我不想在所有按钮上设置它。如果我尝试在delegate中挑出我想要的单元格,tableView:cellForRowAtIndexPath:总是最终成为delegate。如果我单步执行,则在nil加载时正确设置委托,但是当我点击按钮并逐步完成正在发生的事情时,委托是零。

在下面包含我的一些tableView代码。留下一些比特以使其更快阅读。我是否有可能被一些重复使用的东西所困,或者?

//的ViewController

tableView

// Google SSO Button.h

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell = [self configureButtonCell:cell forIndexPath:indexPath];    
    return cell;
}


- (SLPButtonCell *)configureButtonCell:(SLPButtonCell *)cell forIndexPath:(NSIndexPath *)indexPath
{          
    NSDictionary *button = [self.buttons objectAtIndex:indexPath.row];

    cell.delegate = self;

    cell.indexPath = indexPath;
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (button is type 1) {
        //do whatever
    }
    else if (button is type2) {
        [GIDSignIn sharedInstance].uiDelegate = self;
        cell.googleSsoButton.delegate = self;
    }
    else {

    //do whatever


    }
    return cell;

}

- (void)signInWasSuccessful
{
//success code happens here
}
- (void)signInWasUnsuccessful:(NSError *)error
{
//non success happens here
}

// Google SSO Button.m

@protocol GoogleSSOButtonDelegate <NSObject>

- (void)signInWasSuccessful;
- (void)signInWasUnsuccessful:(NSError *)error;

@end

@interface GoogleSSOButton : UIButton

@property (nonatomic, weak) id<GoogleSSOButtonDelegate> delegate;

@end

提供完整的事件序列:

  1. 用户按下登录按钮 - 呼叫登录并触发- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error { if (custom stuff works) { if ([_self.delegate respondsToSelector:@selector(signInWasSuccessful)]){ [_self.delegate signInWasSuccessful]; } } else { if ([_self.delegate respondsToSelector:@selector(signInWasUnsuccessful:)]){ [_self.delegate signInWasUnsuccessful:error]; } } }

  2. 该按钮也是[GIDSignIn sharedInstance].uiDelegate,因此当登录完成后,无论是成功还是不成功,都会返回按钮

  3. GIDSignInDelegate的实施会触发我的自定义GIDSignInDelegate,需要触发顶级delegate

1 个答案:

答案 0 :(得分:0)

要(不)证明我的理论,你需要发布自定义代理代码。你能把它添加到你的问题中吗?

我的猜测是,你在混淆cell.googleSsoButton.delegatecell.delegate

- (SLPButtonCell *)configureButtonCell:(SLPButtonCell *)cell forIndexPath:(NSIndexPath *)indexPath
{          
    // here you set delegate for every cell:
    cell.delegate = self;

    // here you do your conditional
    else if (button is type2) {
        [GIDSignIn sharedInstance].uiDelegate = self;
        cell.googleSsoButton.delegate = self;
    }
}

另外值得注意的是,[GIDSignIn sharedInstance].uiDelegate是一个共享实例/单例 - 你无法有条件地设置它,因为只要你的else语句到达一次,它总是被设置为self。建议将其移入控制器的viewDidLoad并从表视图委托中移出。