There is not way I can explain optionals better than this. Read it twice. Three times or more. It takes a while for it to sink in.
Tag: Swift
Swift – UITableViewRowActions and editActionsForRowAtIndexPath
Do you like those button that display when you swipe a row in a table view to the left? You can add your own with little effort using UITableViewRowAction, and tableView(:editActionsForRowAtIndexPath).
tableView editActionsForRowAtIndexPath is a UITableViewDelegate method. This method returns an array of UITableViewRowAction’s. Each of these row actions includes a style, title, and action. The action receives the index path of the row where the action was executed.
Here is a sample gist:
Swift – Singletons
Singleton and the TodoManager
The goal of the current project is to create a Todo App. This app will work with Todo items that need to be shared across more than one view controller. One approach is to create a single instance of a class that can be shared across the entire app. This is called a Singleton.
What is an instance?
A class file describes a type of object that can be created from that class. Each Object created from a class is called an Instance. For example our app will store Todo items. These are defined in the Todo class.
class Todo {
…
}
A class will define the properties, and methods of an object, and include an initializer.
class Todo {
var name: String
var completed = false
init(name: String) {
self.name = name
}
}
Create an instance of a class by using the name of the class like this.
var somethingTodo = Todo(name: “Eat Breakfast”)
In this case somethingTodo is an object with properties of name, and completed.
Each time you use Todo(name: “”) you are creating a new instance of Todo. Each instance stores it’s own unique values for name and completed.
This method works well for Todo items since we want to create a new and unique entry each time we create a Todo.
TodoManager
If our app contains a list of todos, we need to make these available across multiple View Controllers. If the Todos are stored in an array that belongs to (is a property of) One View Controller it’s very awkward to make todos available to other view controllers.
A better approach is to create a separate class to manage the list of todos. This class will be responsible for holding the list of Todos, relaying the count of todos, adding new todos, deleting todos, etc.
Keeping all of the code that manages Todos in one class helps keep our code organized. All of the methods and properties that manage our list of todo items will be in one place. Imagine the TodoManage class looks something like this:
class TodoManager {
var todos = [Todo]()
var count: Int {
get {
return todos.count
}
}
func addNewTodo(name: String) {
…
}
func getTodoAtIndex(index: Int) -> Todo {
…
}
}
There is one problem. Imagine we have three view controllers:
ListTodoViewController
AddNewTodoViewController
TodoDetailsViewController
Now imagine that each of these creates a new instance of TodoManager:
Here each view controller has it’s own instance of a TodoManager. That’s three unique managers. This won’t work for our app. Imagine that the app adds a new Todo to the manager owned by AddNewTodoManager. The todos array in List, and Details would not be updated to match.
What we need to create is something that looks like this:
Imagine in this arrangement that each ViewController has a manager property that points to the same instance. Now List View controller is displaying the same list of todos that Add new and details are working with.
Really what we will create is something that will look more like this:
Imagine here that TodoManager owns an instance of itself, and other classes can access that instance.
Singletons and Shared instance
Singleton is the name of a software design pattern. A design pattern is a standard solution for common programming problems. Our todo app is trying to solve a standard software problem: we need single instance of a class that can be shared.
Static/Class properties
Normally classes will only use instance properties. In the case of the Todo class, name and completed are instance properties. Instance properties belong to each instance, and each instance stores it’s own unique values for these properties.
Classes can also define static properties. These properties belong to the class, not to each instance! here’s an example class:
class Test {
static var name = “Hello World”
var number = 10
}
The first property is static, and belongs to the class, while the second property is an instance property, which each instance will have.
Test.name // “Hello World”
var instanceOfTest = Test()
instanceOfTest.number // 10
Working with a singleton
The singleton pattern works like this, we’ll use the TodoManager as an example. This class wants to manager a list of Todos that it can share with other classes in our app.
The TodoManager class starts like this:
class TodoManager {
static let sharedInstance = TodoManager()
private init() {
}
}
Notice the property sharedInstance is static. This makes it a class property. You’ll access it with:
TodoManager.sharedInstance
This property is also a constant, let. This means it can only have one value. You can’t set change its value once set.
To complete the pattern we mark the initializer: init() with private. This means that this method is only accessible within this class. You won’t be able to access the initializer from outside of the class.
Swift – NSNumberFormatter
At some point you will find yourself in need of formatting numbers. This could be for time, temperature, currency, or just wanting to control the number of decimal places. You might even want to convert numerals to words. The NSNumberFormatter does all of this.
Figure this is a very common task so, someone will have made a library of code to handle it. The Cocoa Touch framework provides the end all in number formatting in NSNumberFormatter.
Using the NSNumberFormatter is easy though, maybe, not intuitive until you work with it a few times.
The steps are easy:
- Make an instance of the NSNumberFormatter.
- Set options…
- Call the formatter.stringFromNumber() method.
A use case might look like this:
The example above creates a number formatter that converts a value into a currency style. NSNumberFormatter, in this case, should convert “cost” into currency formatted number for the current locale.
This is very sophisticated, and powerful, for very little work on our part.
The second step is where things get hazy. There are many options you can choose from. We can break these down into styles, and options.
You can think of styles as predetermined, standardized ways of expressing numbers, and options as the details that might make up a style.
For example a style might be currency style. This might include options for rounding to two decimal places, and adding a comma every third significant digit, while preceding everything with the correct currency symbol.
Options on the other hand, would things like setting the number of digits before the decimal point, and the number of digits after the decimal point. Setting the character used for the separator, like the “.”, or “,”.
Here are a few examples:
Swift – Simple Animations
Need to create simple animation? Use UIView.animateWithDuration() or one of the other similar methods. While this is fairly easy to use, it is bit cumbersome. Why not make a helper method to simplify your work?
- Imagine a method that takes a UIView as a an argument. Since all UI elements are sub classes of UIView you can pass any UI element.
- For convenience imagine all of the elements were created at the location where they will end their motion. This means our method will offset the element in the x and or y, then move it back to it’s starting point.
- To make the motion interesting and give us some controller we need to pass in the duration.
- If everything is moving at the same time things are dull, and some things are not possible. We need a delay.
Our method looks like this:
func animateThing(thing: UIView, offsetY: CGFloat, offsetX: CGFloat, time: NSTimeInterval, delay: NSTimeInterval) {
// some code here
}
The parameters are
- thing – a UIView or subclass of UIView, which is the thing to animate
- offsetY – CGFloat the amount to offset in the y axis. This sets the starting point on the y axis, thing will move back to original position!
- offsetX – CGFloat the amount to offset on the x axis.
- time – NSTimeInterval, this can be a Double (0.5 for example), it sets the length of the animation in seconds
- delay – NSTimeInterval, this sets the time to wait before beginning the motion.
A few points
- The offsetX, and offsetY can use positive or negative numbers. Negative values move the object left or up. Positive numbers move down, or right. These determine an offset, that places the object at a new position before the motion begins, the object will end its motion at it’s starting point.
- Time is set in seconds. Delay determines how long to wait before the motion begins. The total time of the animation will be time + delay.
- It’s probably best to call this function in viewWillAppear. This way the objects get positioned before we see the view, and the motion will be applied each time the view is shown.
Using an Extension
An extension allows you to add functions to existing classes. Rather than adding this function to each custom view controller we create, using an extension we can add an extension to the UIViewController class, and all ViewControllers will have the new function.
Add the first code example to your project in a file named extensions.swift. You’re done! The second code example shows some usage examples and is not required.
Swift – Camera and UIImagePickerController
Take pictures with the UIImagePickerController. This is a ViewController subclass, that creates a view that allows you to take a picture with the camera.
The UIImagePickerController works with a Delegate to handle working with an image after it has been taken.
Try it for yourself. Create a ViewController with a UIImageView, add an IBOutlet for this. We will use this to display the image, so we need a reference.
Add a UIButton, and add an IBAction. Use this to open the Image Picker controller.
In the button action add:
Parse Swift with Cocoapods
- Xcode new project
- Terminal CD to project directory
- Open your Podfile with: open -a Xcode Podfile
- Uncomment Frameworks, and add Parse, and ParseUI to do. Should look something like this:
- # Uncomment this line to define a global platform for your project
# platform :ios, '8.0' # Uncomment this line if you're using Swift use_frameworks! target 'SpringShowApp' do pod 'Parse' pod 'ParseUI' end
- Quit Xcode
- In terminal: pod install
- When Terminal is finished, open your project from the ProjectName.xcworkspace. From this point on, you will need to open the project from this file!
Swift – Open an Alert box
Opening an alert in iOS is very easy. Use the UIAlertController. This creates a special ViewController that can be displayed in one of two styles Alert, or ActionSheet.
let alert = UIAlertController(title: "Send Cypher", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) let message = UIAlertAction(title: "Message", style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in // Do something when message is tapped } let email = UIAlertAction(title: "Email", style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in // Do something when email is tapped } let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) alert.addAction(message) alert.addAction(email) alert.addAction(cancel) presentViewController(alert, animated: true, completion: nil)