Skip to content

Commit

Permalink
Fixed git ignore
Browse files Browse the repository at this point in the history
  • Loading branch information
tmdvs committed Sep 9, 2016
2 parents 30b21d4 + cda4294 commit aee3830
Show file tree
Hide file tree
Showing 8 changed files with 104 additions and 82 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ profile
\#*\#
*~

/TDBadgedCell.xcodeproj/project.xcworkspace/xcuserdata/
TDBadgedCell.xcodeproj/project.xcworkspace/xcuserdata/
6 changes: 4 additions & 2 deletions README.markdown
Original file line number Diff line number Diff line change
@@ -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:

Expand Down
15 changes: 14 additions & 1 deletion TDBadgedCell.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
};
};
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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";
Expand All @@ -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;
};
Expand All @@ -253,21 +262,25 @@
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;
};
22F678A31D80288C007D2FAE /* Release */ = {
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;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0720"
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
Expand Down
25 changes: 1 addition & 24 deletions TDBadgedCell/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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:.
}


}

25 changes: 18 additions & 7 deletions TDBadgedCell/Base.lproj/Main.storyboard
Original file line number Diff line number Diff line change
@@ -1,24 +1,35 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="9531" systemVersion="15G31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="giq-3r-Yvd">
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11198.2" systemVersion="16A294a" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="giq-3r-Yvd">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9529"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11161"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--TDBaged Cell Examples-->
<!--TDBagedCell Examples-->
<scene sceneID="gCx-I2-Qzz">
<objects>
<tableViewController id="pad-GC-tEL" customClass="ViewController" customModule="TDBadgedCell" customModuleProvider="target" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="xLx-Yx-Pw9">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="BadgedCell" id="ezo-TG-RHv" customClass="TDBadgedCell" customModule="TDBadgedCell" customModuleProvider="target">
<rect key="frame" x="0.0" y="92" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="ezo-TG-RHv" id="CnV-Wn-3rI">
<frame key="frameInset" width="375" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
</tableViewCellContentView>
</tableViewCell>
</prototypes>
<connections>
<outlet property="dataSource" destination="pad-GC-tEL" id="Jbz-dN-ms2"/>
<outlet property="delegate" destination="pad-GC-tEL" id="Von-zJ-z1v"/>
</connections>
</tableView>
<navigationItem key="navigationItem" title="TDBaged Cell Examples" id="Yo5-di-q4y"/>
<navigationItem key="navigationItem" title="TDBagedCell Examples" id="Yo5-di-q4y"/>
</tableViewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="D2Y-pF-Fgv" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
Expand Down
67 changes: 42 additions & 25 deletions TDBadgedCell/TDBadgedCell.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -41,54 +40,72 @@ 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()
}

// 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()
}
}
44 changes: 23 additions & 21 deletions TDBadgedCell/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

0 comments on commit aee3830

Please sign in to comment.