Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swift3 #45

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,6 @@ xcuserdata
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts

Carthage/Build
Carthage/Build
.DS_Store

5 changes: 5 additions & 0 deletions TableViewCellWithAutoLayout.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,9 @@
LastUpgradeCheck = 0700;
ORGANIZATIONNAME = smileyborg;
TargetAttributes = {
99BCDCA018008C0000B8E66B = {
LastSwiftMigration = 0830;
};
99BCDCBB18008C0000B8E66B = {
TestTargetID = 99BCDCA018008C0000B8E66B;
};
Expand Down Expand Up @@ -480,6 +483,7 @@
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "TableViewCellWithAutoLayout/TableViewController/TableViewCellWithAutoLayout-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
WRAPPER_EXTENSION = app;
};
name = Debug;
Expand All @@ -499,6 +503,7 @@
PRODUCT_BUNDLE_IDENTIFIER = "com.smileyborg.${PRODUCT_NAME:rfc1034identifier}";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "TableViewCellWithAutoLayout/TableViewController/TableViewCellWithAutoLayout-Bridging-Header.h";
SWIFT_VERSION = 3.0;
WRAPPER_EXTENSION = app;
};
name = Release;
Expand Down
16 changes: 8 additions & 8 deletions TableViewCellWithAutoLayout/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,39 +12,39 @@ class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let viewController = TableViewController(style: .Plain)
window = UIWindow(frame: UIScreen.main.bounds)
let viewController = TableViewController(style: .plain)
window!.rootViewController = UINavigationController(rootViewController: viewController)
window!.makeKeyAndVisible()
return true
}

func applicationWillResignActive(application: UIApplication)
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)
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)
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)
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)
func applicationWillTerminate(_ application: UIApplication)
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
Expand Down
20 changes: 8 additions & 12 deletions TableViewCellWithAutoLayout/TableViewController/Model.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,34 +14,30 @@ class Model
init(populated: Bool)
{
if (populated) {
for familyName: AnyObject in UIFont.familyNames() {
if let familyNameString = familyName as? String {
dataArray.append((title: familyNameString, body: randomLoremIpsum()))
}
for familyNameString in UIFont.familyNames {
dataArray.append((title: familyNameString, body: randomLoremIpsum()))
}
}
}

func addSingleItem()
{
let fontFamilies = UIFont.familyNames()
let fontFamilies = UIFont.familyNames

let r = random() % fontFamilies.count
let familyName: AnyObject = fontFamilies[r]
let r = Int(arc4random()) % fontFamilies.count
let familyNameString = fontFamilies[r]

if let familyNameString = familyName as? String {
dataArray.append((title: familyNameString, body: randomLoremIpsum()))
}
dataArray.append((title: familyNameString, body: randomLoremIpsum()))
}

func randomLoremIpsum() -> String
{
let loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent non quam ac massa viverra semper. Maecenas mattis justo ac augue volutpat congue. Maecenas laoreet, nulla eu faucibus gravida, felis orci dictum risus, sed sodales sem eros eget risus. Morbi imperdiet sed diam et sodales. Vestibulum ut est id mauris ultrices gravida. Nulla malesuada metus ut erat malesuada, vitae ornare neque semper. Aenean a commodo justo, vel placerat odio. Curabitur vitae consequat tortor. Aenean eu magna ante. Integer tristique elit ac augue laoreet, eget pulvinar lacus dictum. Cras eleifend lacus eget pharetra elementum. Etiam fermentum eu felis eu tristique. Integer eu purus vitae turpis blandit consectetur. Nulla facilisi. Praesent bibendum massa eu metus pulvinar, quis tristique nunc commodo. Ut varius aliquam elit, a tincidunt elit aliquam non. Nunc ac leo purus. Proin condimentum placerat ligula, at tristique neque scelerisque ut. Suspendisse ut congue enim. Integer id sem nisl. Nam dignissim, lectus et dictum sollicitudin, libero augue ullamcorper justo, nec consectetur dolor arcu sed justo. Proin rutrum pharetra lectus, vel gravida ante venenatis sed. Mauris lacinia urna vehicula felis aliquet venenatis. Suspendisse non pretium sapien. Proin id dolor ultricies, dictum augue non, euismod ante. Vivamus et luctus augue, a luctus mi. Maecenas sit amet felis in magna vestibulum viverra vel ut est. Suspendisse potenti. Morbi nec odio pretium lacus laoreet volutpat sit amet at ipsum. Etiam pretium purus vitae tortor auctor, quis cursus metus vehicula. Integer ultricies facilisis arcu, non congue orci pharetra quis. Vivamus pulvinar ligula neque, et vehicula ipsum euismod quis."

let loremIpsumArray = loremIpsum.componentsSeparatedByString(" ")
let loremIpsumArray = loremIpsum.components(separatedBy: " ")

let minimumNumberOfWords = 3
let r = max(minimumNumberOfWords, random() % loremIpsumArray.count) // get a random number r, where: minimumNumberOfWords <= r <= loremIpsumArray.count
let r = max(minimumNumberOfWords, Int(arc4random()) % loremIpsumArray.count) // get a random number r, where: minimumNumberOfWords <= r <= loremIpsumArray.count
let loremIpsumRandom = loremIpsumArray[0..<r] // grab a slice of the lorem ipsum array that contains r number of words

let loremIpsumText = loremIpsumRandom.reduce("") { "\($0) \($1)" } // join the array of words to make a string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class NibTableViewCell: UITableViewCell

func updateFonts()
{
titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
bodyLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2)
titleLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
bodyLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption2)
}
}
38 changes: 19 additions & 19 deletions TableViewCellWithAutoLayout/TableViewController/TableViewCell.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ class TableViewCell: UITableViewCell

var didSetupConstraints = false

var titleLabel: UILabel = UILabel.newAutoLayoutView()
var bodyLabel: UILabel = UILabel.newAutoLayoutView()
var titleLabel: UILabel = UILabel.newAutoLayout()
var bodyLabel: UILabel = UILabel.newAutoLayout()

override init(style: UITableViewCellStyle, reuseIdentifier: String!)
{
Expand All @@ -36,16 +36,16 @@ class TableViewCell: UITableViewCell

func setupViews()
{
titleLabel.lineBreakMode = .ByTruncatingTail
titleLabel.lineBreakMode = .byTruncatingTail
titleLabel.numberOfLines = 1
titleLabel.textAlignment = .Left
titleLabel.textColor = UIColor.blackColor()
titleLabel.textAlignment = .left
titleLabel.textColor = UIColor.black
titleLabel.backgroundColor = UIColor(red: 0, green: 0, blue: 1, alpha: 0.1) // light blue

bodyLabel.lineBreakMode = .ByTruncatingTail
bodyLabel.lineBreakMode = .byTruncatingTail
bodyLabel.numberOfLines = 0
bodyLabel.textAlignment = .Left
bodyLabel.textColor = UIColor.darkGrayColor()
bodyLabel.textAlignment = .left
bodyLabel.textColor = UIColor.darkGray
bodyLabel.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.1) // light red

updateFonts()
Expand All @@ -66,20 +66,20 @@ class TableViewCell: UITableViewCell

// Prevent the two UILabels from being compressed below their intrinsic content height
NSLayoutConstraint.autoSetPriority(UILayoutPriorityRequired) {
self.titleLabel.autoSetContentCompressionResistancePriorityForAxis(.Vertical)
self.bodyLabel.autoSetContentCompressionResistancePriorityForAxis(.Vertical)
self.titleLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.bodyLabel.autoSetContentCompressionResistancePriority(for: .vertical)
}

titleLabel.autoPinEdgeToSuperviewEdge(.Top, withInset: kLabelVerticalInsets)
titleLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: kLabelHorizontalInsets)
titleLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: kLabelHorizontalInsets)
titleLabel.autoPinEdge(toSuperviewEdge: .top, withInset: kLabelVerticalInsets)
titleLabel.autoPinEdge(toSuperviewEdge: .leading, withInset: kLabelHorizontalInsets)
titleLabel.autoPinEdge(toSuperviewEdge: .trailing, withInset: kLabelHorizontalInsets)

// This constraint is an inequality so that if the cell is slightly taller than actually required, extra space will go here
bodyLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: titleLabel, withOffset: 10.0, relation: .GreaterThanOrEqual)
bodyLabel.autoPinEdge(.top, to: .bottom, of: titleLabel, withOffset: 10.0, relation: .greaterThanOrEqual)

bodyLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: kLabelHorizontalInsets)
bodyLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: kLabelHorizontalInsets)
bodyLabel.autoPinEdgeToSuperviewEdge(.Bottom, withInset: kLabelVerticalInsets)
bodyLabel.autoPinEdge(toSuperviewEdge: .leading, withInset: kLabelHorizontalInsets)
bodyLabel.autoPinEdge(toSuperviewEdge: .trailing, withInset: kLabelHorizontalInsets)
bodyLabel.autoPinEdge(toSuperviewEdge: .bottom, withInset: kLabelVerticalInsets)

didSetupConstraints = true
}
Expand All @@ -89,7 +89,7 @@ class TableViewCell: UITableViewCell

func updateFonts()
{
titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
bodyLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2)
titleLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
bodyLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption2)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ class TableViewController: UITableViewController
super.viewDidLoad()

title = "iOS 8 Self Sizing Cells"
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Trash, target: self, action: #selector(TableViewController.clear))
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: #selector(TableViewController.addRow))
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.trash, target: self, action: #selector(TableViewController.clear))
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.add, target: self, action: #selector(TableViewController.addRow))

tableView.allowsSelection = false

Expand All @@ -31,7 +31,7 @@ class TableViewController: UITableViewController
Uncomment ONE of the two lines below to switch between approaches.
Make sure that the other line commented out - don't uncomment both!
*******************************************************************/
tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: kCellIdentifier) // uncomment this line to load table view cells programmatically
tableView.register(TableViewCell.self, forCellReuseIdentifier: kCellIdentifier) // uncomment this line to load table view cells programmatically
// tableView.registerNib(UINib(nibName: "NibTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: kCellIdentifier) // uncomment this line to load table view cells from IB


Expand All @@ -45,62 +45,62 @@ class TableViewController: UITableViewController
tableView.estimatedRowHeight = 44.0 // set this to whatever your "average" cell height is; it doesn't need to be very accurate
}

override func viewDidAppear(animated: Bool)
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TableViewController.contentSizeCategoryChanged(_:)), name: UIContentSizeCategoryDidChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TableViewController.contentSizeCategoryChanged(_:)), name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil)
}

override func viewDidDisappear(animated: Bool)
override func viewDidDisappear(_ animated: Bool)
{
super.viewDidDisappear(animated)

NSNotificationCenter.defaultCenter().removeObserver(self, name: UIContentSizeCategoryDidChangeNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil)
}

// This function will be called when the Dynamic Type user setting changes (from the system Settings app)
func contentSizeCategoryChanged(notification: NSNotification)
func contentSizeCategoryChanged(_ notification: Notification)
{
tableView.reloadData()
}

// Deletes all rows in the table view and replaces the model with a new empty one
func clear()
{
var rowsToDelete: [NSIndexPath] = []
var rowsToDelete: [IndexPath] = []
for i in 0..<model.dataArray.count {
rowsToDelete.append(NSIndexPath(forRow: i, inSection: 0))
rowsToDelete.append(IndexPath(row: i, section: 0))
}

model = Model(populated: false)

tableView.deleteRowsAtIndexPaths(rowsToDelete, withRowAnimation: .Automatic)
tableView.deleteRows(at: rowsToDelete, with: .automatic)
}

// Adds a single row to the table view
func addRow()
{
model.addSingleItem()

let lastIndexPath = NSIndexPath(forRow: model.dataArray.count - 1, inSection: 0)
tableView.insertRowsAtIndexPaths([lastIndexPath], withRowAnimation: .Automatic)
let lastIndexPath = IndexPath(row: model.dataArray.count - 1, section: 0)
tableView.insertRows(at: [lastIndexPath], with: .automatic)
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int
override func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return model.dataArray.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// This will be the case for programmatically loaded cells (see viewDidLoad to switch approaches)
if let cell: TableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? TableViewCell {
if let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: kCellIdentifier) as? TableViewCell {
// Configure the cell for this indexPath
cell.updateFonts()
let modelItem = model.dataArray[indexPath.row]
Expand All @@ -115,7 +115,7 @@ class TableViewController: UITableViewController
}

// This will be the case for interface builder loaded cells (see viewDidLoad to switch approaches)
if let cell: NibTableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? NibTableViewCell {
if let cell: NibTableViewCell = tableView.dequeueReusableCell(withIdentifier: kCellIdentifier) as? NibTableViewCell {
// Configure the cell for this indexPath
cell.updateFonts()
let modelItem = model.dataArray[indexPath.row]
Expand Down