diff --git a/.gitignore b/.gitignore index 3a9c673..22a6231 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,4 @@ profile \#*\# *~ -/TDBadgedCell.xcodeproj/project.xcworkspace/xcuserdata/ +TDBadgedCell.xcodeproj/project.xcworkspace/xcuserdata/ diff --git a/README.markdown b/README.markdown index 3166199..64cad96 100644 --- a/README.markdown +++ b/README.markdown @@ -1,7 +1,9 @@ # TDBadgedCell -TDBadgedCell grew out of the need for TableViewCell badges and the lack of them in iOS (see the [article explaining this on TUAW](http://www.tuaw.com/2010/01/07/iphone-devsugar-simple-table-badges/). Recently the project has been re-written in Swift and much simplified. +TDBadgedCell grew out of the need for TableViewCell badges and the lack of them in iOS (see the [article explaining this on TUAW](http://www.tuaw.com/2010/01/07/iphone-devsugar-simple-table-badges/). Recently the project has been re-written in Swift and much simplified. -![Example Image](http://up.tmdvs.me/hO59/d) +***Note:*** *You can find the old Objective-C version on the [deprecetated-objective-c branch](https://github.com/tmdvs/TDBadgedCell/tree/deprecated-objective-c)*. + +![Example Image](http://up.tmdvs.me/hOlw/d) To set the content of your badge (String) simply do: diff --git a/TDBadgedCell.xcodeproj/project.pbxproj b/TDBadgedCell.xcodeproj/project.pbxproj index 30619b3..892e5e7 100644 --- a/TDBadgedCell.xcodeproj/project.pbxproj +++ b/TDBadgedCell.xcodeproj/project.pbxproj @@ -94,11 +94,13 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0720; - LastUpgradeCheck = 0720; + LastUpgradeCheck = 0800; ORGANIZATIONNAME = "Tim Davies"; TargetAttributes = { 22F678781D80288B007D2FAE = { CreatedOnToolsVersion = 7.2; + DevelopmentTeam = W376QLUK5J; + LastSwiftMigration = 0800; }; }; }; @@ -179,10 +181,13 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; @@ -224,10 +229,13 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; @@ -244,6 +252,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 9.2; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -253,10 +262,12 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + DEVELOPMENT_TEAM = W376QLUK5J; INFOPLIST_FILE = TDBadgedCell/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.tmdvs.TDBadgedCell; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -264,10 +275,12 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + DEVELOPMENT_TEAM = W376QLUK5J; INFOPLIST_FILE = TDBadgedCell/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.tmdvs.TDBadgedCell; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Release; }; diff --git a/TDBadgedCell.xcodeproj/xcuserdata/tim.xcuserdatad/xcschemes/TDBadgedCell.xcscheme b/TDBadgedCell.xcodeproj/xcuserdata/tim.xcuserdatad/xcschemes/TDBadgedCell.xcscheme index 9d27dde..59788cd 100644 --- a/TDBadgedCell.xcodeproj/xcuserdata/tim.xcuserdatad/xcschemes/TDBadgedCell.xcscheme +++ b/TDBadgedCell.xcodeproj/xcuserdata/tim.xcuserdatad/xcschemes/TDBadgedCell.xcscheme @@ -1,6 +1,6 @@ Bool { + private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } - func applicationWillResignActive(application: UIApplication) { - // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. - } - - func applicationDidEnterBackground(application: UIApplication) { - // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. - } - - func applicationWillEnterForeground(application: UIApplication) { - // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. - } - - func applicationDidBecomeActive(application: UIApplication) { - // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - } - - func applicationWillTerminate(application: UIApplication) { - // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. - } - - } diff --git a/TDBadgedCell/Base.lproj/Main.storyboard b/TDBadgedCell/Base.lproj/Main.storyboard index 6b5b334..98f7de7 100644 --- a/TDBadgedCell/Base.lproj/Main.storyboard +++ b/TDBadgedCell/Base.lproj/Main.storyboard @@ -1,24 +1,35 @@ - - + + - + + - + - + - + + + + + + + + + + + - + diff --git a/TDBadgedCell/TDBadgedCell.swift b/TDBadgedCell/TDBadgedCell.swift index 6e7d62e..a2e6db2 100644 --- a/TDBadgedCell/TDBadgedCell.swift +++ b/TDBadgedCell/TDBadgedCell.swift @@ -19,20 +19,19 @@ class TDBadgedCell: UITableViewCell { } else { self.contentView.addSubview(badgeView) self.drawBadge() - self.layoutSubviews() } } } // Badge background colours - var badgeColour = UIColor(red: 0, green: 0.478, blue: 1, alpha: 1.0) - var badgeColorHighlighted = UIColor.whiteColor() + var badgeColor : UIColor = UIColor(red: 0, green: 0.478, blue: 1, alpha: 1.0) + var badgeColorHighlighted : UIColor = .darkGray // Font and style - var badgeFontSize = 11.0; - var badgeRadius = 20; - var badgeOffset = CGPointMake(10, 0); - let badgeView = UIImageView() + var badgeFontSize : Float = 11.0; + var badgeRadius : Float = 20; + var badgeOffset = CGPoint(x:10, y:0); + private let badgeView = UIImageView() override func layoutSubviews() { super.layoutSubviews() @@ -41,17 +40,24 @@ class TDBadgedCell: UITableViewCell { if(self.contentView.frame.width != self.frame.width) { badgeOffset.x = 0 // Accessory types are a pain to get sizing for? } + badgeView.frame.origin.x = floor(self.contentView.frame.width - badgeView.frame.width - badgeOffset.x) badgeView.frame.origin.y = floor((self.frame.height / 2) - (badgeView.frame.height / 2)) + + // Now lets update the width of the cells text labels to take the badge into account + self.textLabel?.frame.size.width -= badgeView.frame.width + (badgeOffset.x * 2) + if((self.detailTextLabel) != nil) { + self.detailTextLabel?.frame.size.width -= badgeView.frame.width + (badgeOffset.x * 2) + } } // When the badge - override func setHighlighted(highlighted: Bool, animated: Bool) { + override func setHighlighted(_ highlighted: Bool, animated: Bool) { super.setHighlighted(highlighted, animated: animated) drawBadge() } - override func setSelected(selected: Bool, animated: Bool) { + override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) drawBadge() } @@ -59,36 +65,47 @@ class TDBadgedCell: UITableViewCell { // Draw the bagde image private func drawBadge() { // Calculate the size of our string - let textSize : CGSize = NSString(string: badgeString).sizeWithAttributes([NSFontAttributeName:UIFont.boldSystemFontOfSize(CGFloat(badgeFontSize))]) + let textSize : CGSize = NSString(string: badgeString).size(attributes:[NSFontAttributeName:UIFont.boldSystemFont(ofSize:CGFloat(badgeFontSize))]) // Create a frame with padding for our badge let height = textSize.height + 10 - let width = textSize.width + 16 - let badgeFrame : CGRect = CGRectMake(0, 0, (width > height) ? width : height, height) + var width = textSize.width + 16 + if(width < height) { + width = height + } + let badgeFrame : CGRect = CGRect(x:0, y:0, width:width, height:height) let badge = CALayer() badge.frame = badgeFrame - badge.backgroundColor = ((self.highlighted || self.selected) ? badgeColorHighlighted : badgeColour).CGColor + + if(self.isHighlighted || self.isSelected) { + badge.backgroundColor = badgeColorHighlighted.cgColor + } else { + badge.backgroundColor = badgeColor.cgColor + } + badge.cornerRadius = (CGFloat(badgeRadius) < (badge.frame.size.height / 2)) ? CGFloat(badgeRadius) : CGFloat(badge.frame.size.height / 2) // Draw badge into graphics context - UIGraphicsBeginImageContextWithOptions(badge.frame.size, false, UIScreen.mainScreen().scale) - let ctx = UIGraphicsGetCurrentContext() - CGContextSaveGState(ctx) - badge.renderInContext(ctx!) - CGContextSaveGState(ctx) + UIGraphicsBeginImageContextWithOptions(badge.frame.size, false, UIScreen.main.scale) + let ctx = UIGraphicsGetCurrentContext()! + ctx.saveGState() + badge.render(in:ctx) + ctx.saveGState() // Draw string into graphics context - CGContextSetBlendMode(ctx, CGBlendMode.Clear) - NSString(string: badgeString).drawInRect(CGRectMake(8, 5, textSize.width, textSize.height), withAttributes: [ - NSFontAttributeName:UIFont.boldSystemFontOfSize(CGFloat(badgeFontSize)), - NSForegroundColorAttributeName: UIColor.clearColor() - ]) + ctx.setBlendMode(CGBlendMode.clear) + NSString(string: badgeString).draw(in:CGRect(x:8, y:5, width:textSize.width, height:textSize.height), withAttributes: [ + NSFontAttributeName:UIFont.boldSystemFont(ofSize:CGFloat(badgeFontSize)), + NSForegroundColorAttributeName: UIColor.clear + ]) - let badgeImage = UIGraphicsGetImageFromCurrentImageContext() + let badgeImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() - badgeView.frame = CGRectMake(0, 0, badgeImage.size.width, badgeImage.size.height) + badgeView.frame = CGRect(x:0, y:0, width:badgeImage.size.width, height:badgeImage.size.height) badgeView.image = badgeImage + + self.layoutSubviews() } } diff --git a/TDBadgedCell/ViewController.swift b/TDBadgedCell/ViewController.swift index 6418c6c..bee1591 100644 --- a/TDBadgedCell/ViewController.swift +++ b/TDBadgedCell/ViewController.swift @@ -12,47 +12,49 @@ class ViewController: UITableViewController { let demoItems : [[String:String]] = [ ["title" : "This is an example badge", "badge": "1"], - ["title" : "This is a second example badge", "badge": "25"], + ["title" : "This is a second example badge", "badge": "123"], ["title" : "A text badge", "badge": "Warning!"], - ["title" : "Another text badge", "badge": "Danger!"], + ["title" : "Another text badge with a really long title!", "badge": "Danger!"], ] - override func viewDidLoad() { - super.viewDidLoad() - self.tableView.delegate = self - self.tableView.dataSource = self - } - override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return demoItems.count } - override func numberOfSectionsInTableView(tableView: UITableView) -> Int { - return 1 - } - - override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> TDBadgedCell { - var cell : TDBadgedCell? = tableView.dequeueReusableCellWithIdentifier("BadgedCell") as! TDBadgedCell?; + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> TDBadgedCell { + var cell : TDBadgedCell? = tableView.dequeueReusableCell(withIdentifier:"BadgedCell") as! TDBadgedCell?; if((cell == nil)) { - cell = TDBadgedCell(style: .Default, reuseIdentifier: "BadgedCell"); + cell = TDBadgedCell(style: .default, reuseIdentifier: "BadgedCell"); } - // Set accessory views for two badges - if(indexPath.row < 2) { - cell?.accessoryType = .DisclosureIndicator - } cell?.textLabel!.text = demoItems[indexPath.row]["title"] cell?.badgeString = demoItems[indexPath.row]["badge"]! + // Set accessory views for two badges + if(indexPath.row == 0) { + cell?.accessoryType = .disclosureIndicator + } + + if(indexPath.row == 1) { + cell?.accessoryType = .checkmark + } + // Set background colours for two badges if(indexPath.row == 2) { - cell?.badgeColour = UIColor.orangeColor() + cell?.badgeColor = .orange } else if(indexPath.row == 3) { - cell?.badgeColour = UIColor.redColor() + cell?.badgeColor = .red } return cell! } + + override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { + tableView.deselectRow(at: indexPath, animated: true) + } + } }