SwiftUI – State change in UITextField causes the frameWidth to grow uncontrolled and ignore bounds/frame

You need to decrease priority of content resistance in makeUIView (so content would not push external layout set in SwiftUI) like below func makeUIView(context: UIViewRepresentableContext<MyField>) -> UITextField { let field = UITextField(frame: .zero) field.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) …

Calculate age from birth date using NSDateComponents in Swift

You get an error message because 0 is not a valid value for NSCalendarOptions. For “no options”, use NSCalendarOptions(0) or simply nil: let ageComponents = calendar.components(.CalendarUnitYear, fromDate: birthday, toDate: now, options: nil) let age = ageComponents.year (Specifying nil is possible because NSCalendarOptions conforms to the RawOptionSetType protocol which in turn inherits from NilLiteralConvertible.) Update for … Read more

Singleton in Swift

The standard singleton pattern is: final class Manager { static let shared = Manager() private init() { … } func foo() { … } } And you’d use it like so: Manager.shared.foo() Credit to appzYourLife for pointing out that one should declare it final to make sure it’s not accidentally subclassed as well as the … Read more

Deleting a Row from a UITableView in Swift?

Works for Swift 3 and Swift 4 Use the UITableViewDataSource tableView(:commit:forRowAt:) method, see also this answer here: func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { print(“Deleted”) self.catNames.remove(at: indexPath.row) self.tableView.deleteRows(at: [indexPath], with: .automatic) } }

How to detect a tap gesture location in SwiftUI?

Well, after some tinkering around and thanks to this answer to a different question of mine, I’ve figured out a way to do it using a UIViewRepresentable (but by all means, let me know if there’s an easier way!) This code works for me! struct ContentView : View { @State var points:[CGPoint] = [CGPoint(x:0,y:0), CGPoint(x:50,y:50)] … Read more

Convert a two byte UInt8 array to a UInt16 in Swift

If you want to go via NSData then it would work like this: let bytes:[UInt8] = [0x01, 0x02] println(“bytes: \(bytes)”) // bytes: [1, 2] let data = NSData(bytes: bytes, length: 2) print(“data: \(data)”) // data: <0102> var u16 : UInt16 = 0 ; data.getBytes(&u16) // Or: let u16 = UnsafePointer<UInt16>(data.bytes).memory println(“u16: \(u16)”) // u16: 513 … Read more

unwrapping multiple optionals in if statement

Great news. Unwrapping multiple optionals in a single line is now supported in Swift 1.2 (XCode 6.3 beta, released 2/9/15). No more tuple/switch pattern matching needed. It’s actually very close to your original suggested syntax (thanks for listening, Apple!) if let email = emailField?.text, password = passwordField?.text { } Another nice thing is you can … Read more