Rounded Corner Button in Swift

It’s very simple to create buttons with rounded corners. Create a button like you normally would in Interface Builder, create an Outlet to it, and then in viewDidLoad, set the attributes like this: button.layer.borderWidth = 3.0 button.layer.borderColor = UIColor.white.cgColor // Set this to the background color of your button button.layer.cornerRadius = 8.0

Play Music in iOS

Here’s a utility to play background music for iOS in Swift: First, import AVFoundation. Then add: var backgroundMusicPlayer: AVAudioPlayer! func playBackgroundMusic(filename: String) { let resourceUrl = Bundle.main.url(forResource: filename, withExtension: nil) guard let url = resourceUrl else { print(“Could not find file: \(filename)”) return } do { try backgroundMusicPlayer = AVAudioPlayer(contentsOf: url) backgroundMusicPlayer.numberOfLoops = -1 //… Continue reading Play Music in iOS

Basic init rules in Swift

I kept wondering whether you’re supposed to call the parent init method before or after your code and I found a basic answer: init() { // Put values into your instance variables and constants super.init() // Other initialization code, such as calling methods, goes here }  

Categorized as hints Tagged ,

Generic Alert Method

Here is a generic alert method that you can place in a global functions/variables file that checks for an existing alert first. func showAlert(withTitle title: String, message: String, viewController: UIViewController) { if viewController.presentedViewController == nil { // Prevent multiple alerts at the same time let localizedTitle = NSLocalizedString(title, comment: “”) let localizedMessage = NSLocalizedString(message, comment:… Continue reading Generic Alert Method

Get Timestamps

This is just a random method I’m no longer using and wanted to get rid of but didn’t really want to throw it away in case I want to reference it someday. static func getTimestamps(forEntry entry: Entry?) -> [String: Int] { let calendar = NSCalendar.currentCalendar() let formatter = NSDateFormatter() formatter.dateFormat = “yyyy-MM-dd HH:mm:ss” var since… Continue reading Get Timestamps

Trim whitespace from a string in Swift

let whitespaceSet = NSCharacterSet.whitespaceCharacterSet() let trimmedString = myTextField.text!.stringByTrimmingCharactersInSet(whitespaceSet) if trimmedString.characters.count == 0 { print(“myTextField is blank”) }  

Embed Tab Bar Controller in Navigation Controller

I don’t think you’re really supposed to do this since the option is grayed out in Xcode when you select Editor -> Embed in Navigation Controller, but a hacky way to get around it is to control-drag from a free-standing Navigation Controller to the Tab Bar Controller and select “root view controller.”

Add Tab to Tab Bar Controller

Control-click from the Tab Bar Controller to the controller you want to be the new tab and select “view controllers.”