Home > Mobile >  How to add red dot badge in table view cell?
How to add red dot badge in table view cell?

Time:03-30

Try to add red dot badge for every unread data in inbox tableviewcell.

I try using cell.accessoryview to add badge

        let size: CGFloat = 9
        let width = max(size, 0.7 * size * 1) // perfect circle is smallest allowed
        let badge = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: size))
       
        badge.layer.cornerRadius = size / 2
        badge.layer.masksToBounds = true
        badge.textAlignment = .center
        badge.textColor = UIColor.white
        badge.backgroundColor = UIColor.red
        if viewModel.sortedInboxItems[indexPath.section].isRead {
            cell.accessoryView = badge
        }

But if using cell.accessoryview it will change the display like image below (TIME in the right corner of the cell is moving forward). How to make it not change the display?

enter image description here

EDIT

Try to create dot as uilabel in custom uitableview cell like image below

enter image description here

But the result show like this image below. The red dot shape is not good enough? Can someone help with this issue ?

enter image description here

CodePudding user response:

The accessoryView is not part of the contentView of the cell. If you set the accessoryView it will push the contentView over to make room for itself. More information on that can be found cell structure

If you don't want it to do this, put your red dot into the cell itself instead of using the accessoryView. It's unclear how you've built your cells, but it looks like you've created a custom UITableViewCell, so you should be able to do this without trouble.

Or as commented above, you could include your time label in your accessory view alongside the red dot if applicable.

CodePudding user response:

Consider using a UIView with corner radius just like you did with the label. To make sure that the shape is right (sizes have initialised properly) change its corner radius in an overriden layoutSubviews.

override func layoutSubviews() {
    super.layoutSubviews()
    badgeInboxView.layer.cornerRadius = badgeInboxView.frame.height/2
}
  • Related