简体   繁体   中英

Objective-C: App-wide fully reusable custom UITableViewCell

Hi, this question has been asked many times however I was never able to find a proper solution for the following:

I have a custom UITableViewCell which shows the user profile picture and a 'Follow'/'Following' button. I reuse this cell in around 10 UIViewControllers / UITableViewControllers throughout the app.

Now to my question: Adding the 'Following' button action logic (ie a server call to follow or unfollow the user) in the UITableViewCell class would be against MVC so I currently add the action to the button in tableView:cellForRowAtIndexPath: and call the necessary code inside the UIViewController action method eg - (void)followUnfollowUser:(id)sender . (The actual server call is in an external class with static methods but the call to this is still in the followUnfollowUser:(id)sender method)

What this means is every time I need to use the custom UITableViewCell I need to add this code to the controller. Except for the UI logic (which is allowed in the UITableViewCell class) I don't see any reuse. Why should an action related to the UITableViewCell be in the UIViewController ? Is there a way I can just reuse the custom UITableViewCell without having to rewrite the follow/unfollow action?

Thanks

Just implement the button inside a cell and handle the action there. From view controller that creates a cell all you need to do is to call some kind of model update on your custom cell - that will allow cell to call API directly from inside - or whatever is action doing in your application can be coded directly inside custom cell class.

If you need any feedback to UIViewController to reload view or smth - add either a delegate that will be called when user click on those elements or use NSNotificationCenter for that purpose.

You can use Delegate or Block

Create a property and assign the code from the View Controller, then run on the button click run it

@property (nonatomic, strong) void (^loginCompletionBlock)(BOOL);
@property (nonatomic, copy) void (^inviteBlock)(NSDictionary*result);

- (IBAction)click:(id)sender{
    if(self.inviteBlock){
        self.inviteBlock(data);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM