When a customer replaces a short order note with a long one, the card may show half an emoji, clip text from the last line, or change height while scrolling. When your team takes on this kind of issue on a cloud Mac, do not start by adjusting line height. First, turn the original text, available width, and font settings into a fixed test fixture. Prove that the line-breaking loop neither skips nor repeats text and never splits a character, then check the final rendering in the iOS control.
Define the measurement contract first
This article covers rich-text components that implement their own line breaking with Core Text. Its measurements are not intended to apply directly to every system control. For each measurement, record at least the original text, font and font size, content width, paragraph style, language, and runtime version. Width is measured in points after subtracting left and right padding, not in screenshot pixels.
Range units are a common source of mistakes: Core Text string ranges use UTF-16, so Swift’s String.count is not a valid substitute for the length. A single visible character can span multiple code units; emoji sequences and text with combining accents both expose this error.
Use the macOS fixture to verify the algorithm’s contract and the iOS runtime to verify the final layout. Passing on both platforms does not mean they must produce the same number of lines.
Build an executable line-breaking fixture
Save the following as WrapCheck.swift on a node that already has the command-line developer tools installed. The code uses the system font, checks that every line has a positive length and stays within bounds, and verifies that each new starting position falls on a boundary between complete composed character sequences. An empty string may return an empty result.
import Foundation
import CoreText
enum LayoutError: Error {
case invalidWidth
case stalled(Int)
case outOfBounds(Int)
case splitCharacter(Int)
}
func wrap(_ text: String, width: Double) throws -> [[String: Int]] {
guard width.isFinite, width > 0 else {
throw LayoutError.invalidWidth
}
let source = text as NSString
let font = CTFontCreateUIFontForLanguage(.system, 17, nil)!
let key = NSAttributedString.Key(kCTFontAttributeName as String)
let value = NSAttributedString(string: text, attributes: [key: font])
let typesetter = CTTypesetterCreateWithAttributedString(value)
var offset = 0
var rows: [[String: Int]] = []
while offset < source.length {
let count = CTTypesetterSuggestLineBreak(typesetter, offset, width)
guard count > 0 else {
throw LayoutError.stalled(offset)
}
guard count <= source.length - offset else {
throw LayoutError.outOfBounds(offset)
}
let end = offset + count
if end < source.length {
let cluster = source.rangeOfComposedCharacterSequence(at: end)
guard cluster.location == end else {
throw LayoutError.splitCharacter(end)
}
}
rows.append(["location": offset, "length": count])
offset = end
}
return rows
}
let samples = [
"",
"订单备注:请在送达前联系收件人。",
"Cafe\u{301} 👩🏽💻 家庭👨👩👧👦",
"first\r\nsecond\n",
String(repeating: "W", count: 80)
]
var report: [[String: Any]] = []
for (index, text) in samples.enumerated() {
for width in [48.0, 120.0, 240.0] {
report.append([
"sample": index,
"width": width,
"ranges": try wrap(text, width: width)
])
}
}
let data = try JSONSerialization.data(
withJSONObject: report,
options: [.prettyPrinted, .sortedKeys]
)
try data.write(to: URL(fileURLWithPath: "wrap-report.json"), options: .atomic)
Run xcrun swift WrapCheck.swift. An uncaught error causes the process to fail; the report is generated only on success. The pipeline must use the exit status to determine the result, not assume the current run passed because a JSON file from a previous run remains in the directory. Use a separate artifact directory for every run.
Test narrow columns separately from invalid inputs
The widths above are test inputs, not recommended layout dimensions. Add zero, negative values, and non-finite values, and expect them to take the invalid-parameter path rather than being silently replaced with a default width. Tests must catch and verify the error type, not count every error as a pass.
Define a separate product policy for extremely narrow positive widths. When a complete character cannot fit, you can show a truncation indicator, allow the complete character to overflow, or reject the layout. Whichever policy you choose, never patch the loop with “add one when the length is zero.” Adding one may skip only half a surrogate pair and permanently misalign the remaining ranges.
Include consecutive spaces, tabs, trailing newlines, and very long text without spaces in the fixture set as well. If the component creates an additional blank line for a newline character, define that behavior explicitly in the display layer. Do not infer the number of visible lines directly from the number of ranges in the report.
Recheck fonts and height on iOS
Move the same inputs into the app’s test target and call the actual layout entry point. The macOS script provides a quick preflight check; iOS tests must use the fonts, paragraph styles, and container widths the app actually uses. If a custom font has not loaded, the test should fail rather than let font fallback hide the problem.
Assert height and width separately
Create a CTLine for each actual line range, read its ascent, descent, and leading with CTLineGetTypographicBounds, then accumulate the height using the component’s own baseline rules. Do not replace measurement with “line count times font size”: attachments, fallback fonts, and paragraph spacing can all change the result.
Width checks must also distinguish typographic advance width from glyph ink bounds. Italic glyphs may extend beyond the advance boundary, while trailing whitespace may increase the measured width. Specify which width the component constrains before writing assertions, so valid typography is not mistaken for an overflow.
Hand off reproducible failure cases
Keep a separate fixture set for each customer project. A failure record should include the commit identifier, escaped text, total UTF-16 length, font configuration, width, and failing range. Before adding order notes to shared artifacts, replace any personal information with synthetic text that preserves the same structure.
Check four things during acceptance: the ranges cover the entire text continuously from zero; the loop always advances or fails explicitly; every split preserves complete characters; and the target iOS control does not clip the last line. After a runtime upgrade, compare these contracts first, then manually review changes in line count. Do not simply accept all new snapshots in bulk.
The final deliverable is a set of inputs and validation rules that reproduce the problem, not a screenshot that happens to look correct on one machine.
Frequently asked questions
Does passing the macOS fixture guarantee identical iOS wrapping?
No. It validates range coverage, character integrity, and termination. Check final line counts, fallback fonts, and rendering in the actual control on the target iOS runtime.
Can a stalled layout loop advance by one UTF-16 code unit?
No. That can split a surrogate pair or a composed character sequence. Report a layout failure or apply an explicit fallback that preserves complete character sequences.
Add a cloud Mac for your project
Dedicated Apple Silicon M4 physical nodes, available by the day, week, month, or quarter. Your rental stops at the end of the term—no idle machines after your project wraps up.
Choose a rental term