-1

Thanks to @jsetting32 I have a custom UITableViewCell complete with buttons at the bottom of the tableView. However, when I am clicking those buttons, the value for the selectedState is not changing, making it a bit difficult for the end-user to tell if they have clicked it or not.

self.likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.likeButton addTarget:self action:@selector(didTapLikeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.likeButton setTitle:@"Pray" forState:UIControlStateNormal];
[self.likeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.likeButton setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
[[self.likeButton titleLabel] setFont:[UIFont fontWithName:@"Verdana" size:12.0f]];
[self.cellView addSubview:self.likeButton];
4

4 回答 4

1

所以这就是我解决按钮问题的方法......您的自定义单元格中应该已经有一个方法可以设置类似的状态......它是这样设置的

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellIdentifier = @"cellIdentifier";

    if (indexPath.row == [self.objects count])
        return [self tableView:tableView cellForNextPageAtIndexPath:indexPath];

    PHChatCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[PHChatCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        [cell setDelegate:self];
    }

    [self setCellAttributesWithCell:cell withObject:[self.object objectAtIndex:indexPath.row] withIndexPath:indexPath];

    return cell;
}


- (void)setCellAttributesWithCell:(PHChatCell *)cell withObject:(PFObject *)object withIndexPath:(NSIndexPath *)indexPath
{
    if (object) {
        [cell setChat:object];
        [cell setTag:indexPath.row];
        [cell.likeButton setTag:indexPath.row];

        if ([[PHCache sharedCache] attributesForMessage:object]) {
            [cell setLikeStatus:[[PHCache sharedCache] isMessageLikedByCurrentUser:object]];

            NSString *likeCount = [[[PHCache sharedCache] likeCountForMessage:object] description];
            cell.likeCount.text = ([likeCount isEqualToString:@"1"]) ?
            [NSString stringWithFormat:@"%@ like", likeCount] :
            [NSString stringWithFormat:@"%@ likes", likeCount];

            NSString *commentCount = [[[PHCache sharedCache] commentCountForMessage:object] description];
            cell.commentCount.text = ([commentCount isEqualToString:@"1"]) ?
            [NSString stringWithFormat:@"%@ comment", commentCount] :
            [NSString stringWithFormat:@"%@ comments", commentCount];
            return;
        }

        @synchronized(self) {
            // Put this in your init method
            // self.outstandingSectionHeadersQueries = [NSMutableDictionary dictionary]
            if (![self.outstandingSectionHeaderQueries objectForKey:@(indexPath.row)]) {
                PFQuery *query = [PHUtility queryForActivitiesOnMessage:object cachePolicy:kPFCachePolicyNetworkOnly];
                [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                    @synchronized(self) {
                        [self.outstandingSectionHeaderQueries removeObjectForKey:@(indexPath.row)];

                        if (error) return;

                        NSMutableArray *likers = [NSMutableArray array];
                        NSMutableArray *commenters = [NSMutableArray array];

                        BOOL isLikedByCurrentUser = NO;

                        for (PFObject *activity in objects) {
                            if ([[activity objectForKey:kPHActivityTypeKey] isEqualToString:kPHActivityTypeLike] && [activity objectForKey:kPHActivityFromUserKey]) {
                                [likers addObject:[activity objectForKey:kPHActivityFromUserKey]];
                            } else if ([[activity objectForKey:kPHActivityTypeKey] isEqualToString:kPHActivityTypeComment] && [activity objectForKey:kPHActivityFromUserKey]) {
                                [commenters addObject:[activity objectForKey:kPHActivityFromUserKey]];
                            }

                            if ([[[activity objectForKey:kPHActivityFromUserKey] objectId] isEqualToString:[[PFUser currentUser] objectId]] &&
                                [[activity objectForKey:kPHActivityTypeKey] isEqualToString:kPHActivityTypeLike]) {
                                isLikedByCurrentUser = YES;
                            }
                        }

                        [[PHCache sharedCache] setAttributesForMessage:object likers:likers commenters:commenters likedByCurrentUser:isLikedByCurrentUser];

                        if (cell.tag != indexPath.row) return;

                        [cell setLikeStatus:[[PHCache sharedCache] isMessageLikedByCurrentUser:object]];

                        NSString *likeCount = [[[PHCache sharedCache] likeCountForMessage:object] description];
                        cell.likeCount.text = ([likeCount isEqualToString:@"1"]) ?
                        [NSString stringWithFormat:@"%@ like", likeCount] : [NSString stringWithFormat:@"%@ likes", likeCount];

                        NSString *commentCount = [[[PHCache sharedCache] commentCountForMessage:object] description];
                        cell.commentCount.text = ([commentCount isEqualToString:@"1"]) ?
                        [NSString stringWithFormat:@"%@ comment", commentCount] : [NSString stringWithFormat:@"%@ comments", commentCount];
                    }
                }];
            }
        }
    }
}


- (void)PHChatCell:(PHChatCell *)cell didTapLikeButton:(UIButton *)button chat:(PFObject *)chat
{
    // Disable the button so users cannot send duplicate requests
    [cell shouldEnableLikeButton:NO];

    //These are private interface properties to handle when the user wants to unlike the prayer
    //when the UIActionsheet is loaded
    self.chat = chat;
    self.likeButton = button;
    self.cell = cell;

    if (button.selected) {
        [[[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Unlike" otherButtonTitles:nil] showInView:self.view];
        return;
    }

    BOOL liked = !button.selected;
    [cell setLikeStatus:liked];

    NSString *originalButtonTitle = button.titleLabel.text;
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

    NSNumber *likeCount = [numberFormatter numberFromString:button.titleLabel.text];
    [button setTitle:@"Liked" forState:UIControlStateNormal];

    [UIView animateWithDuration:0.25 animations:^{
        [cell.likeImage setImage:[UIImage imageNamed:@"ButtonLikeSelected.png"]];
        [cell.likeImage setTransform:CGAffineTransformMakeScale(1.5, 1.5)];
    } completion:^(BOOL finished){
        [UIView animateWithDuration:0.25 animations:^{
            [cell.likeImage setTransform:CGAffineTransformMakeScale(1, 1)];
        }];
    }];

    NSInteger checker = [[cell.likeCount text] integerValue] + 1;
    cell.likeCount.text = (checker == 1) ?
    [NSString stringWithFormat:@"%ld like", (long)checker] :
    [NSString stringWithFormat:@"%ld likes", (long)checker];
    likeCount = [NSNumber numberWithInt:[likeCount intValue] + 1];

    [[PHCache sharedCache] incrementLikerCountForMessage:chat];
    [[PHCache sharedCache] setMessageIsLikedByCurrentUser:chat liked:liked];
    [PHUtility likeMessageInBackground:chat block:^(BOOL succeeded, NSError *error) {
        PHChatCell *actualCell = (PHChatCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:button.tag inSection:0]];
        [actualCell shouldEnableLikeButton:YES];
        [actualCell setLikeStatus:succeeded];

        if (!succeeded) {
            [actualCell.likeButton setTitle:originalButtonTitle forState:UIControlStateNormal];
        }
    }];
}
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {

        BOOL liked = !self.likeButton.selected;
        [self.cell setLikeStatus:liked];

        [self.likeButton setTitle:@"Like" forState:UIControlStateNormal];
        [self.cell.likeImage setImage:[UIImage imageNamed:@"ButtonLike.png"]];

        NSInteger checker = [[self.cell.likeCount text] integerValue] - 1;
        self.cell.likeCount.text = (checker == 1) ?
        [NSString stringWithFormat:@"%ld like", (long)checker] :
        [NSString stringWithFormat:@"%ld likes", (long)checker];

        NSString *originalButtonTitle = self.likeButton.titleLabel.text;
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        NSNumber *likeCount = [numberFormatter numberFromString:self.likeButton.titleLabel.text];
        likeCount = [NSNumber numberWithInt:[likeCount intValue] + 1];
        if ([likeCount intValue] > 0) {
            likeCount = [NSNumber numberWithInt:[likeCount intValue] - 1];
        }

        [[PHCache sharedCache] decrementLikerCountForMessage:self.chat];
        [[PHCache sharedCache] setMessageIsLikedByCurrentUser:self.chat liked:NO];
        [PHUtility unlikeMessageInBackground:self.chat block:^(BOOL succeeded, NSError *error) {
            PHChatCell *actualCell = (PHChatCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.likeButton.tag inSection:0]];
            [actualCell shouldEnableLikeButton:YES];
            [actualCell setLikeStatus:!succeeded];

            if (!succeeded) {
                [actualCell.likeButton setTitle:originalButtonTitle forState:UIControlStateNormal];
            }
        }];
    }
}

这是前面代码片段中使用的查询方法(在 PHUtility 类中声明):

+ (PFQuery *)queryForActivitiesOnMessage:(PFObject *)message cachePolicy:(PFCachePolicy)cachePolicy {
    PFQuery *queryLikes = [PFQuery queryWithClassName:kPHActivityClassKey];
    [queryLikes whereKey:kPHActivityMessageKey equalTo:message];
    [queryLikes whereKey:kPHActivityTypeKey equalTo:kPHActivityTypeLike];

    PFQuery *queryComments = [PFQuery queryWithClassName:kPHActivityClassKey];
    [queryComments whereKey:kPHActivityMessageKey equalTo:message];
    [queryComments whereKey:kPHActivityTypeKey equalTo:kPHActivityTypeComment];

    PFQuery *query = [PFQuery orQueryWithSubqueries:[NSArray arrayWithObjects:queryLikes,queryComments,nil]];
    [query setCachePolicy:cachePolicy];
    [query includeKey:kPHActivityFromUserKey];
    [query includeKey:kPHActivityMessageKey];

    return query;
}

这是PHCache实现...

@interface PHCache()

@property (nonatomic, strong) NSCache *cache;
- (void)setAttributes:(NSDictionary *)attributes forMessage:(PFObject *)message;
@end

@implementation PHCache
@synthesize cache;

#pragma mark - Initialization

+ (id)sharedCache {
    static dispatch_once_t pred = 0;
    __strong static id _sharedObject = nil;
    dispatch_once(&pred, ^{
        _sharedObject = [[self alloc] init];
    });
    return _sharedObject;
}

- (id)init {
    self = [super init];
    if (self) {
        self.cache = [[NSCache alloc] init];
    }
    return self;
}

- (void)clear {
    [self.cache removeAllObjects];
}
- (void)setAttributes:(NSDictionary *)attributes forMessage:(PFObject *)message {
    [self.cache setObject:attributes forKey:[self keyForMessage:message]];
}
- (NSString *)keyForMessage:(PFObject *)message {
    return [NSString stringWithFormat:@"message_%@", [message objectId]];
}

#pragma mark - Global Chat
- (void)setAttributesForMessage:(PFObject *)message
                         likers:(NSArray *)likers
                     commenters:(NSArray *)commenters
             likedByCurrentUser:(BOOL)likedByCurrentUser {
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [NSNumber numberWithBool:likedByCurrentUser],kPHMessageAttributesIsLikedByCurrentUserKey,
                                @([likers count]),kPHMessageAttributesLikeCountKey,
                                likers,kPHMessageAttributesLikersKey,
                                @([commenters count]),kPHMessageAttributesCommentCountKey,
                                commenters,kPHMessageAttributesCommentersKey,
                                nil];
    [self setAttributes:attributes forMessage:message];
}

- (NSDictionary *)attributesForMessage:(PFObject *)message {
    return [self.cache objectForKey:[self keyForMessage:message]];
}

- (NSNumber *)likeCountForMessage:(PFObject *)message {
    NSDictionary *attributes = [self attributesForMessage:message];
    if (attributes) {
        return [attributes objectForKey:kPHMessageAttributesLikeCountKey];
    }

    return [NSNumber numberWithInt:0];
}

- (NSNumber *)commentCountForMessage:(PFObject *)message {
    NSDictionary *attributes = [self attributesForMessage:message];
    if (attributes) {
        return [attributes objectForKey:kPHMessageAttributesCommentCountKey];
    }

    return [NSNumber numberWithInt:0];
}

- (NSArray *)likersForMessage:(PFObject *)message {
    NSDictionary *attributes = [self attributesForMessage:message];
    if (attributes) {
        return [attributes objectForKey:kPHMessageAttributesLikersKey];
    }

    return [NSArray array];
}

- (NSArray *)commentersForMessage:(PFObject *)message {
    NSDictionary *attributes = [self attributesForMessage:message];
    if (attributes) {
        return [attributes objectForKey:kPHMessageAttributesCommentersKey];
    }

    return [NSArray array];
}

- (void)setMessageIsLikedByCurrentUser:(PFObject *)message liked:(BOOL)liked {
    NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
    [attributes setObject:[NSNumber numberWithBool:liked] forKey:kPHMessageAttributesIsLikedByCurrentUserKey];
    [self setAttributes:attributes forMessage:message];
}

- (BOOL)isMessageLikedByCurrentUser:(PFObject *)message {
    NSDictionary *attributes = [self attributesForMessage:message];
    if (attributes) {
        return [[attributes objectForKey:kPHMessageAttributesIsLikedByCurrentUserKey] boolValue];
    }

    return NO;
}

- (void)incrementLikerCountForMessage:(PFObject *)message {
    NSNumber *likerCount = [NSNumber numberWithInt:[[self likeCountForMessage:message] intValue] + 1];
    NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
    [attributes setObject:likerCount forKey:kPHMessageAttributesLikeCountKey];
    [self setAttributes:attributes forMessage:message];
}

- (void)decrementLikerCountForMessage:(PFObject *)message {
    NSNumber *likerCount = [NSNumber numberWithInt:[[self likeCountForMessage:message] intValue] - 1];
    if ([likerCount intValue] < 0) {
        return;
    }
    NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
    [attributes setObject:likerCount forKey:kPHMessageAttributesLikeCountKey];
    [self setAttributes:attributes forMessage:message];
}

- (void)incrementCommentCountForMessage:(PFObject *)message {
    NSNumber *commentCount = [NSNumber numberWithInt:[[self commentCountForMessage:message] intValue] + 1];
    NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
    [attributes setObject:commentCount forKey:kPHMessageAttributesCommentCountKey];
    [self setAttributes:attributes forMessage:message];
}

- (void)decrementCommentCountForMessage:(PFObject *)message {
    NSNumber *commentCount = [NSNumber numberWithInt:[[self commentCountForMessage:message] intValue] - 1];
    if ([commentCount intValue] < 0) {
        return;
    }
    NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
    [attributes setObject:commentCount forKey:kPHMessageAttributesCommentCountKey];
    [self setAttributes:attributes forMessage:message];
}

- (NSNumber *)messageCountForUser:(PFUser *)user {
    NSDictionary *attributes = [self attributesForUser:user];
    if (attributes) {
        NSNumber *photoCount = [attributes objectForKey:kPHUserAttributesMessageCountKey];
        if (photoCount) {
            return photoCount;
        }
    }

    return [NSNumber numberWithInt:0];
}

- (void)setMessageCount:(NSNumber *)count user:(PFUser *)user {
    NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForUser:user]];
    [attributes setObject:count forKey:kPHUserAttributesMessageCountKey];
    [self setAttributes:attributes forUser:user];
}

就像我在你之前的帖子中所说的那样......它需要大量的代码才能使这个功能“最佳”......缓存对象的原因是限制对服务器的 api 请求。如果单元格已加载,我们将检查缓存以查看单元格的属性是否已加载,如果尚未向服务器查询以获取属性并设置缓存以确保我们不需要将来发出api请求......

所有以开头的变量kPH都是常量,你可以自己声明,或者你觉得如何就足够了……就像我之前说的,检查 Anypic 项目并将这些功能集成到你的应用程序中是最好的。只需将 PAPCache 类和 PAPUtility 类复制过来。只需确保您阅读了代码以完全了解发生了什么,从而更好地了解如何将代码与您的代码集成,并对其进行扩展以向您的应用程序添加更多功能。

如果您有任何问题,请随时发表评论。

于 2015-01-09T17:15:50.333 回答
1

尝试UIControlStateHighlighted代替UIControlStateSelected

[self.likeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.likeButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
于 2015-01-09T16:55:04.947 回答
1

一世。触摸时使用 UIControlStateHighlighted,如上所述。ii. 保持不同的颜色:由于您有一个自定义 UITableViewCell,您应该实现一个 IBAction 并将您的 UIButton 设置为此使用

[self.likeButton addTarget:self action:@selector(select:) forControlEvents:UIControlEventTouchUpInside];

在单元组的 .m 文件中:

-(IBAction)onSelectCellClicked:(id)sender {
   if(self.yourButton.selected) {
      self.yourButton.selected = NO;
    } else {
      self.yourButton.selected = YES;
    }
}

在将其放入单元格的 .h 文件后,现在将单元格的委托设置为单元格中的 self :

@protocol CustomCellDelegate <NSObject>
@end

@interface CustomCell : UITableViewCell
@property (strong, nonatomic) NSObject<CustomCellDelegate>* delegate;

@end

并放入使用自定义单元格呈现 UITableView 的 VC。

于 2015-01-09T22:06:57.283 回答
0

您可以将此行添加到'didTapLikeButtonAction' 中

self.likeButton.selected = !self.likeButton.selected;

一旦你改变了选中的状态,按钮就会改变它的标题颜色。

您可能还想添加此行以获得更平滑的效果:

[self.likeButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
于 2015-01-09T17:21:51.213 回答