首页 > 代码库 > 如何添加badgeview

如何添加badgeview

首先我们需要用到JSBadgeView这个第三方库,在需要用到的类文件中导入;

然后我们需要给badge绑定一个数据,用来显示数字,我采用如下方法将值暂存,在需要显示时取出来;

NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];

                NSString *notCount = [pref stringForKey:@"notbadge"];取出值

                notice.strNoticeCount += 1;新的值

                int notSum = notCount.intValue + notice.strNoticeCount;新的加上旧的

                NSString *notBadge = [NSString stringWithFormat:@"%d",notSum];

                [pref setValue:notBadge forKey:@"notbadge"];再存入user

然后在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中,给需要用到的cell绑定;

if (tableView.tag == 100) {

        

        if (arrayNotice.count>0) {

            if (indexPath.row == 0) {

                NSString *simpleTableIdentifier = @"NoticeCell";

 

                MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

                UIImageView* imageView = (UIImageView*)[cell.contentView viewWithTag:100];找不到这个tag就会新建,找到了就沿用,节省内存

if (imageView == nil) {

                    imageView = [[UIImageView alloc]initWithFrame:CGRectMake(leftedge, topedge, CELL_HEIGHT -5, CELL_HEIGHT-5)];这个图是类似头像的,badge就绑定在这个图上,

                    [imageView setTag:100];

                    [cell.contentView addSubview:imageView];

                    JSBadgeView *badgeView =  [[JSBadgeView alloc] initWithParentView:imageView alignment:JSBadgeViewAlignmentTopRight];

                    [badgeView setTag:200];

 在设置cell的方法中加上

JSBadgeView *badgeView = (JSBadgeView*)  [imageView viewWithTag:200];

                NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];

                NSString *badgeCount = [pref stringForKey:@"notbadge"];

                badgeView.badgeText = badgeCount;

                if ([badgeView.badgeText isEqualToString:@"0"]) {

                    [badgeView setHidden:YES];

                }

 这样就可以显示了,

当我点进去是需要清空这个值并且隐藏,由于我是用的segue所以在- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

用identifier判断

else if( [segue.identifier isEqualToString:@"openNotice"]){

        NSIndexPath *indexPath = [self.tableMessage indexPathForCell:(UITableViewCell *)sender];

        

        NoticeViewController *noticeview = segue.destinationViewController;

        MessageCell *cell =(MessageCell *) [self.tableMessage cellForRowAtIndexPath:indexPath];

        JSBadgeView *badgeView = (JSBadgeView*) [cell.contentView viewWithTag:200];

        badgeView.badgeText = @"0";

        NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];

        [pref setValue:0 forKey:@"notbadge"];

        if ([badgeView.badgeText isEqualToString:@"0"]) {

            [badgeView setHidden:YES];

        }

 这样就可以了,当然如果别的方法中会改变这个badge的值也需要将第一个方法中的代码写进去,删除cell时也别忘记清空这个值,