Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift, How to add Badges on UIImageView in TableViewCell in TableView?

I am developing a social networking site where I have a TableView with multiple cells(rows), in each cell I have a "comment" and "like" Imageview, so whenever update comes from the server I have to increment the number of "comment" and "like" through badges. So how to add badges on UIImageView in TableViewCell in Swift

like image 836
Chaitra Deshpande Avatar asked Apr 06 '16 05:04

Chaitra Deshpande


1 Answers

You can add Badge on UIImageView this way

func drawImageView(mainImage: UIImage, withBadge badge: UIImage) -> UIImage
{
    UIGraphicsBeginImageContextWithOptions(mainImage.size, false, 0.0)
    mainImage.drawInRect(CGRectMake(0, 0, mainImage.size.width, mainImage.size.height))
    badge.drawInRect(CGRectMake(mainImage.size.width - badge.size.width, 0, badge.size.width, badge.size.height))

    let resultImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return resultImage
}

and then use this function

    let mainImage = UIImage(named: "main_image_name_here")
    let badgeImage = UIImage(named: "badge_icon_name_here")
    let myBadgedImage: UIImage = drawImageView(mainImage!, withBadge: badgeImage!)
    myImageView.image = myBadgedImage//set Image on ImageView
like image 145
swiftBoy Avatar answered Oct 29 '22 03:10

swiftBoy