Nine iOS notes from June 2019, checked again: label borders, where a CGColor doesn't follow dark mode; rounded labels that stay round when Auto Layout resizes them; reading a web page as text without garbling UTF-8; why checking the screen height to guess the iPhone model breaks; the "Could not load NIB in bundle" crash, reproduced; copying a Realm List; segmented control corners and fonts (set the selected state too); and capitalizing the first letter without lowercasing "iPhone".
SWIFT TIPS · UIKIT · 9 NOTES
First posted on June 20, 2019, as "9 Notes for me in June Swift 4.2". Rewritten on November 19, 2026. The tests were run as Mac Catalyst programs with Swift 6.2.3 (Xcode 26.2, Swift 5 mode) on macOS 26.0.1, and every code block was type-checked for an iOS 15 target, except the Realm snippet, which I didn't compile because Realm isn't installed here. Nothing was run on an iPhone or a simulator.
June 2019 was a month of small UI fixes: borders, corner radius, segmented controls, a capital letter, plus one crash and a Realm note. The fix I wrote down for the crash was "recreate the files and don't copy the code". It worked, but it didn't say why, so this rewrite reproduces the crash and names the actual causes.
Each note below shows what the 2019 version said, then what holds today, with a test where one was possible.
1. A border around a label
2019: label.layer.borderColor = UIColor.green.cgColor and label.layer.borderWidht = 2.0.
Now: the property is borderWidth; the 2019 spelling doesn't compile:
Border.swift:2:44: error: value of type 'CALayer' has no member 'borderWidht'
The bigger catch arrived with dark mode in iOS 13. A layer's border color is a CGColor, which is one fixed color. A dynamic color like .separator has a light and a dark version, but converting it to CGColor picks one:
UIColor.separator as cgColor, light: 0.00 0.00 0.00 | dark: 1.00 1.00 1.00
a CGColor stored on the layer is fixed: 0.00 0.00 0.00
So a border set once stays black when the person switches to dark mode. Set it again when the appearance changes. This label does that on iOS 15 and 16 with traitCollectionDidChange, which is deprecated in iOS 17, and on iOS 17 and later with registerForTraitChanges:
import UIKit
final class TagLabel: UILabel {
var borderColor: UIColor = .separator { didSet { applyBorder() } }
override init(frame: CGRect) {
super.init(frame: frame)
layer.borderWidth = 1
applyBorder()
if #available(iOS 17.0, *) {
registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (label: TagLabel, _: UITraitCollection) in
label.applyBorder()
}
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
layer.borderWidth = 1
applyBorder()
}
// iOS 15 and 16 call this; on iOS 17 and later the registration above does the job.
override func traitCollectionDidChange(_ previous: UITraitCollection?) {
super.traitCollectionDidChange(previous)
if #unavailable(iOS 17.0) { applyBorder() }
}
private func applyBorder() {
// A CGColor is a fixed color: resolve the dynamic UIColor for the current appearance.
layer.borderColor = borderColor.resolvedColor(with: traitCollection).cgColor
}
}
The same applies to shadowColor and to any other color you hand to a layer.
2. Corner radius from Interface Builder
2019: two ways. Add layer.cornerRadius under User Defined Runtime Attributes in the Identity inspector, or add an @IBInspectable Boolean in an extension that sets the radius to half the height when it's on.
Now: the runtime attribute still works for a fixed radius, and it's still handy for a quick change. The @IBInspectable version has a timing problem: it runs once, while the xib is loading, with the size from the xib. If Auto Layout later makes the label taller, the radius doesn't follow:
height 40 -> cornerRadius 20.0
height 60 -> cornerRadius 30.0
2019 approach after the same resize -> cornerRadius 20.0
The 2019 approach kept 20 after the label grew to 60 points; a subclass that sets the radius in layoutSubviews followed it. Its getter also always returned false, so Interface Builder showed the switch as off even when it was on.
import UIKit
/// A label with fully rounded ends at any height, also when Auto Layout resizes it.
final class PillLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
clipsToBounds = true // UILabel needs this for the background to be clipped
layer.cornerCurve = .continuous
}
required init?(coder: NSCoder) {
super.init(coder: coder)
clipsToBounds = true
layer.cornerCurve = .continuous
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.height / 2
}
}
clipsToBounds matters on a label: without it, the corner radius doesn't clip the label's background color. cornerCurve = .continuous, from iOS 13, gives the smoother corner shape Apple uses for its own controls.
3. Read a web page as text
2019: NSString(contentsOf:encoding:) with isoLatin1, then the HTML-to-attributed-string extension from the May notes.
Now: two problems. NSString(contentsOf:) downloads on the calling thread, so on the main thread it freezes the screen. And ISO Latin-1 is the wrong guess for most of the web, which is UTF-8. I decoded a UTF-8 page containing "Café" both ways:
UTF-8 page read as isoLatin1: <html><body><p>Caf\u{C3}\u{A9}</p></body></html>
UTF-8 page read as UTF-8 : <html><body><p>Caf\u{E9}</p></body></html>
Latin-1 turned "é" into two characters, "é". This function downloads with URLSession, uses the charset the server declares when there is one, and falls back to UTF-8:
import Foundation
enum PageError: Error { case badStatus(Int) }
func fetchHTML(from url: URL) async throws -> String {
let (data, response) = try await URLSession.shared.data(from: url)
if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {
throw PageError.badStatus(http.statusCode)
}
// Most pages are UTF-8; use the charset from the response when the server sends one.
if let name = response.textEncodingName {
let cfEncoding = CFStringConvertIANACharSetNameToEncoding(name as CFString)
if cfEncoding != kCFStringEncodingInvalidId {
let encoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(cfEncoding))
if let text = String(data: data, encoding: encoding) { return text }
}
}
return String(decoding: data, as: UTF8.self)
}
If you then convert the HTML to an attributed string, pass the encoding there as well, as the May 2019 notes show, and do the conversion on the main thread.
4. Checking the device type
2019: a switch on UIScreen.main.nativeBounds.height: 1136 is an iPhone 5, 1334 an iPhone 6, 7 or 8, 2436 an iPhone X or XS, and so on.
Now: the list stopped at the iPhone XR, and every new size since falls into default. Some heights are shared: an iPhone X and an iPhone 11 Pro report the same 2436. It also misses iPads in Split View, where the app is narrower than the screen. And UIScreen.main is deprecated in the iOS 26 SDK, which says to find the screen through the view's window scene instead.
Layout should depend on the space the view actually has, which the size class and bounds tell you. If you need the model for analytics or a bug report, read the hardware identifier, such as "iPhone15,2", and map it on your server:
import UIKit
final class GalleryViewController: UIViewController {
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Decide from the space you actually have, not from the device model.
let columns = view.bounds.width >= 700 ? 4 : (view.bounds.width >= 400 ? 3 : 2)
print("columns:", columns)
}
var isCompactWidth: Bool { traitCollection.horizontalSizeClass == .compact }
}
/// For analytics only: the hardware identifier, such as "iPhone15,2".
func hardwareIdentifier() -> String {
var info = utsname()
uname(&info)
return withUnsafeBytes(of: &info.machine) { buffer in
String(decoding: buffer.prefix { $0 != 0 }, as: UTF8.self)
}
}
5. "Could not load NIB in bundle"
2019: the app crashed with this message for a view called TermsCondition. The fix I found was to delete the .xib and .swift files and create them again without copying code across.
Now: I reproduced the crash by asking for a xib that isn't in the bundle:
Bundle.main.path(forResource: "TermsCondition", ofType: "nib") -> nil
Calling instantiate(withOwner:) ...
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </path/to/MyApp.app> (loaded)' with name 'TermsCondition''
The message means UIKit looked in that bundle for a compiled TermsCondition.nib and didn't find one. Recreating the files fixed it in 2019 because the new xib was added to the app target. The usual causes, in the order I'd check them:
- Target Membership. Select the xib and look at the File inspector. If the app target isn't ticked, the xib isn't copied into the app.
- The name.
nibNamemust match the file name exactly, and file names are case-sensitive on a device even when they aren't on your Mac. - The bundle. A xib in a framework or Swift package isn't in
Bundle.main. UseBundle(for: SomeClass.self), orBundle.modulein a package.
This loader checks first and fails with a message that says which of these to look at:
import UIKit
extension UIView {
/// Loads the first view from a xib with the same name as the class.
/// Fails with a clear message instead of the "Could not load NIB in bundle" crash.
static func loadFromNib() -> Self {
let name = String(describing: self)
let bundle = Bundle(for: self) // also right when the view lives in a framework
guard bundle.path(forResource: name, ofType: "nib") != nil else {
fatalError("\(name).xib is missing from \(bundle.bundlePath): check Target Membership")
}
guard let view = UINib(nibName: name, bundle: bundle)
.instantiate(withOwner: nil).first as? Self else {
fatalError("The first view in \(name).xib is not a \(name)")
}
return view
}
}
// let terms = TermsConditionView.loadFromNib()
6. Copy a Realm List into an array
2019: loop over a Realm List and append each element to a Swift array, from a Stack Overflow answer.
Now: the 2019 loop appended a variable called manual instead of the loop item, so it didn't compile as written, and it force-unwrapped the optional list. A List is a collection, so Array(list) copies it in one step. I didn't compile this one, because Realm isn't installed here:
let options = realm.objects(DataArray.self).first?.options
let copied: [DataArray] = options.map { Array($0) } ?? []
// Changing the List itself needs a write transaction:
try realm.write {
options?.append(newItem)
}
The array holds the same live Realm objects, not copies; use freeze() if you want a snapshot that can cross threads. Realm itself has changed hands since: MongoDB deprecated Atlas Device Sync and the Realm SDKs in September 2024, and the realm-swift README now points to version 20, without sync, as the version to install. The latest release on GitHub is v20.0.6, from September 2026.
7. A segmented control with rounded corners
2019: set layer.cornerRadius, borderColor, borderWidth and masksToBounds, in code or as runtime attributes.
Now: iOS 13 redesigned the segmented control with its own rounded track and a sliding selected segment, so many apps no longer need custom corners. The color of the selected segment is selectedSegmentTintColor, also from iOS 13. A larger radius with masksToBounds still works when your design calls for it; the code is in note 8, together with the fonts.
8. Fonts in a segmented control
2019: in Swift 4.2, NSFontAttributeName became NSAttributedString.Key.font: setTitleTextAttributes([.font: UIFont.systemFont(ofSize: 16)], for: .normal).
Now: right, but it only sets the normal state. The test shows the selected state has no attributes of its own after that call:
normal font size: 16.0 | selected attributes set: no (nil)
after setting .selected too: 16.0
selectedSegmentTintColor set: true
When the selected state has no attributes, what the control draws for it is up to UIKit, so a design that wants the same font, or a heavier one, should set both states:
import UIKit
@MainActor
func styleSegmentedControl(_ control: UISegmentedControl) {
control.selectedSegmentTintColor = .systemBlue
control.setTitleTextAttributes([
.font: UIFont.systemFont(ofSize: 16),
.foregroundColor: UIColor.label
], for: .normal)
control.setTitleTextAttributes([
.font: UIFont.systemFont(ofSize: 16, weight: .semibold),
.foregroundColor: UIColor.white
], for: .selected)
// A border and a custom corner radius, as in the 2019 note:
control.layer.borderWidth = 1
control.layer.borderColor = UIColor.systemBlue.cgColor
control.layer.cornerRadius = 15
control.layer.masksToBounds = true
}
9. Capitalize the first letter
2019: an extension from Stack Overflow, prefix(1).uppercased() + self.lowercased().dropFirst().
Now: it works for the example, but it lowercases the rest of the string, which is a different thing from what the name says:
"data in" -> 2019: "Data in" | keeps the rest: "Data in" | capitalized: "Data In"
"iPhone XR is here" -> 2019: "Iphone xr is here" | keeps the rest: "IPhone XR is here" | capitalized: "Iphone Xr Is Here"
"\u{E9}clair" -> 2019: "\u{C9}clair" | keeps the rest: "\u{C9}clair" | capitalized: "\u{C9}clair"
"iPhone XR is here" became "Iphone xr is here". Without the lowercased(), only the first letter changes. capitalized is something else again: it capitalizes every word. Pick the one you mean; the file keeps both, under names that say what they do:
import Foundation
extension String {
/// "iPhone XR is here" stays "IPhone XR is here"; "data in" becomes "Data in".
func capitalizingFirstLetter() -> String {
prefix(1).uppercased() + dropFirst()
}
/// The 2019 version: also lowercases the rest, so "iPhone XR" becomes "Iphone xr".
func capitalizingFirstLetterOnly() -> String {
prefix(1).uppercased() + lowercased().dropFirst()
}
mutating func capitalizeFirstLetter() {
self = capitalizingFirstLetter()
}
}
For text shown in the interface, also check whether the language capitalizes at all. uppercased(with:) and capitalized(with:) take a locale, which matters for Turkish, where "i" becomes "İ".
What the 2019 version said
The post had five screenshots. One showed the crash log from note 5 with another company's app name in it, so I left it out; the crash is shown as text above. The other four, from Interface Builder:




Keep reading on JR Devhub
Comments