<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vadimahols on Medium]]></title>
        <description><![CDATA[Stories by Vadimahols on Medium]]></description>
        <link>https://medium.com/@vadimahols?source=rss-a25c682d6e74------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*beblNvKJ3nBxhd_8</url>
            <title>Stories by Vadimahols on Medium</title>
            <link>https://medium.com/@vadimahols?source=rss-a25c682d6e74------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:44:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vadimahols/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Switching LTR to RTL at Runtime in UIKit: A Five-Minute Adventure That Wasn’t]]></title>
            <link>https://medium.com/@vadimahols/switching-ltr-to-rtl-at-runtime-in-uikit-a-five-minute-adventure-that-wasnt-55a38932931f?source=rss-a25c682d6e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/55a38932931f</guid>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[right-to-left]]></category>
            <dc:creator><![CDATA[Vadimahols]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 13:19:55 GMT</pubDate>
            <atom:updated>2026-10-21T13:19:55.429Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why changing a single property can leave your iOS app stuck between two layout directions.</em></p><p>I could probably describe my experience with runtime RTL switching using one famous line:</p><p><strong>“A quick five-minute adventure. In and out.”</strong></p><p>If you’ve watched Rick and Morty, you know exactly how that usually ends.</p><p>The task sounded simple enough: let users switch between English and Arabic without restarting the app, losing their navigation stack, or resetting the current screen.</p><p>UIKit already supports right-to-left layouts. Auto Layout understands leading and trailing. System controls know how to mirror themselves. There’s even a property specifically designed to control layout direction.</p><p>What could possibly go wrong?</p><p>Quite a lot, apparently.</p><p>At one point, UIKit was confidently reporting that the interface was running right-to-left.</p><pre>window.effectiveUserInterfaceLayoutDirection == .rightToLeft<br>// true</pre><p>Meanwhile, parts of the UI were still behaving as if nothing had changed.</p><p>Some views moved correctly. Others didn’t. Navigation looked fine until you noticed the back arrow. Text fields became particularly interesting when users started typing English inside an Arabic interface.</p><p>And switching back to English didn’t necessarily restore everything.</p><p>That’s when I stopped looking for a magic property and started investigating how UIKit actually handles layout direction.</p><h3>The Obvious Solution</h3><p>UIKit provides semanticContentAttribute, which controls how a view interprets its content direction.</p><p>So the first attempt is straightforward:</p><pre>window.semanticContentAttribute = .forceRightToLeft</pre><p>Let’s check the result:</p><pre>print(window.effectiveUserInterfaceLayoutDirection)<br>// rightToLeft</pre><p>Looks promising.</p><p>Now let’s update the layout:</p><pre>window.rootViewController?.view.setNeedsLayout()<br>window.rootViewController?.view.layoutIfNeeded()</pre><p>And something does happen.</p><p>Views using directional constraints can move to their new positions. Some system components adapt automatically. Parts of the interface look exactly as expected.</p><p>But other parts remain unchanged.</p><p>A label moves to the right side of the screen while its text stays left-aligned. A custom navigation icon points in the wrong direction. A component that worked perfectly after a cold launch behaves differently when the language changes at runtime.</p><p>My first assumption was that UIKit simply hadn’t updated the entire view hierarchy.</p><p>Maybe forcing another layout pass would fix it.</p><p>It didn’t.</p><p>And the reason is fairly straightforward once you think about what layoutIfNeeded() actually does.</p><p>It performs pending layout work.</p><p>It doesn’t rebuild attributed strings, replace images, or recalculate arbitrary values that your components cached during initialization.</p><p>If a view calculated isRTL once and stored the result, changing its parent’s semantic direction won’t automatically update that property.</p><p>The problem wasn’t a missing layout pass.</p><p>Something else was going on.</p><h3>One Screen, Two Layout Directions</h3><p>Every UIView exposes two properties worth investigating:</p><pre>view.semanticContentAttribute<br>view.effectiveUserInterfaceLayoutDirection</pre><p>They sound similar, but they tell us different things.</p><p>semanticContentAttribute describes the semantic behavior assigned to a view.</p><p>effectiveUserInterfaceLayoutDirection tells us which direction UIKit has resolved for that view.</p><p>Those values aren’t necessarily equivalent.</p><p>Consider this hierarchy:</p><pre>UIWindow<br>  semantic: forceRightToLeft<br>  effective: RTL</pre><pre>  RootView<br>    semantic: unspecified<br>    effective: RTL</pre><pre>    ContentView<br>      semantic: forceLeftToRight<br>      effective: LTR</pre><p>This is a simplified example, but the behavior is valid.</p><p>The window forces RTL.</p><p>The root view inherits that direction.</p><p>But ContentView explicitly forces LTR, overriding the direction inherited from its parent.</p><p>And this is where old implementation decisions start causing trouble.</p><p>In an application that originally supported only left-to-right languages, someone might have added .forceLeftToRight to fix a specific layout issue.</p><p>Everything worked.</p><p>Years later, runtime Arabic localization arrives, and that innocent-looking property suddenly becomes a problem.</p><p>To investigate this, I used a small recursive helper:</p><pre>func inspectLayoutDirection(<br>    _ view: UIView,<br>    depth: Int = 0<br>) {<br>    let indentation = String(<br>        repeating: &quot;  &quot;,<br>        count: depth<br>    )</pre><pre>    print(<br>        &quot;\(indentation)\(type(of: view))&quot;,<br>        &quot;semantic:&quot;,<br>        view.semanticContentAttribute.rawValue,<br>        &quot;effective:&quot;,<br>        view.effectiveUserInterfaceLayoutDirection.rawValue<br>    )</pre><pre>    view.subviews.forEach {<br>        inspectLayoutDirection(<br>            $0,<br>            depth: depth + 1<br>        )<br>    }<br>}</pre><p>It quickly reveals views that explicitly override the surrounding direction.</p><p>For ordinary interface components, .unspecified is usually the better default.</p><p>It allows UIKit to resolve the direction from the surrounding context.</p><p>That fixes one category of problems.</p><p>But it doesn’t explain everything.</p><p>Because even when the relevant views report RTL, some components may still behave as if the app is running in LTR.</p><p>So where are they getting that direction from?</p><h3>UIKit Has Another Source of Truth</h3><p>This was the most interesting part of the investigation.</p><p>Besides semanticContentAttribute, UIKit also exposes layout direction through its trait system:</p><pre>traitCollection.layoutDirection</pre><p>Now imagine the following sequence:</p><ol><li>The application launches in English.</li><li>UIKit creates the initial interface in LTR.</li><li>The user switches to Arabic.</li><li>We force the window’s semantic direction to RTL.</li></ol><p>Let’s inspect the result:</p><pre>let effectiveDirection =<br>    window.effectiveUserInterfaceLayoutDirection</pre><pre>let traitDirection =<br>    window.traitCollection.layoutDirection</pre><p>Depending on the application’s configuration, these values can differ.</p><p>For example:</p><pre>effectiveDirection: rightToLeft<br>traitDirection: leftToRight</pre><p>At first, this looks like UIKit contradicting itself.</p><p>But these properties represent different mechanisms.</p><p>semanticContentAttribute influences how a particular view resolves its layout direction.</p><p>UITraitCollection describes characteristics of the environment provided by UIKit.</p><p>Changing a window’s semantic attribute doesn’t guarantee that its trait collection will change.</p><p>We can inspect the scene as well:</p><pre>let sceneDirection =<br>    window.windowScene?<br>        .traitCollection<br>        .layoutDirection</pre><p>The scene may still report LTR.</p><p>And unlike a view’s semantic attribute, UIWindowScene.traitCollection.layoutDirection doesn’t have a public setter that lets us simply assign a new value.</p><p>That distinction matters.</p><p>Imagine two custom components.</p><p>The first determines its direction using:</p><pre>view.effectiveUserInterfaceLayoutDirection</pre><p>The second uses:</p><pre>traitCollection.layoutDirection</pre><p>If those values differ, the components may make opposite decisions.</p><p>One places an icon on the right.</p><p>The other places it on the left.</p><p>Both are following their own implementation logic.</p><p><strong>The mismatch itself isn’t necessarily a UIKit bug. The problem starts when an application treats different sources of layout direction as interchangeable.</strong></p><p>This also explains why launching directly into Arabic can behave differently from switching to Arabic after the interface has already been created.</p><p>During a cold launch, components have a chance to initialize with the intended direction.</p><p>During a runtime switch, some of them may continue using values calculated earlier.</p><p>And that leads to another question.</p><p>How do we tell those components that the direction has changed?</p><h3>Why traitCollectionDidChange Doesn’t Always Help</h3><p>The natural idea is to observe changes in the trait environment.</p><p>Older UIKit code often uses:</p><pre>override func traitCollectionDidChange(<br>    _ previousTraitCollection: UITraitCollection?<br>) {<br>    super.traitCollectionDidChange(<br>        previousTraitCollection<br>    )</pre><pre>    updateInterface()<br>}</pre><p>But changing semanticContentAttribute doesn’t necessarily change the trait collection.</p><p>Therefore, UIKit isn’t required to call traitCollectionDidChange whenever the effective semantic direction changes.</p><p>On iOS 17 and later, UIKit provides a more modern API for observing trait changes:</p><pre>registerForTraitChanges(<br>    [UITraitLayoutDirection.self]<br>) { (view: UIView, _) in<br>    view.updateInterface()<br>}</pre><p>This is useful when the layout-direction trait actually changes.</p><p>It doesn’t turn semantic attribute changes into trait changes.</p><p>So neither approach should be treated as a universal notification mechanism for runtime RTL switching.</p><p>That was an important realization.</p><p>If the application owns the language switch, it should also own the event that tells dependent components to update.</p><p>Relying entirely on UIKit callbacks leaves gaps.</p><p>And those gaps become particularly obvious when dealing with text.</p><h3>Auto Layout Moved the Label. The Text Stayed Behind.</h3><p>Consider a label with an attributed string:</p><pre>let paragraphStyle = NSMutableParagraphStyle()<br>paragraphStyle.alignment = .left</pre><pre>let attributedText = NSAttributedString(<br>    string: &quot;Example&quot;,<br>    attributes: [<br>        .paragraphStyle: paragraphStyle<br>    ]<br>)</pre><pre>label.attributedText = attributedText</pre><p>After switching to RTL, Auto Layout may correctly reposition the label.</p><p>But the text remains left-aligned.</p><p>Why?</p><p>Because we explicitly told it to.</p><p>The paragraph style still contains .left.</p><p>Calling:</p><pre>label.setNeedsLayout()<br>label.setNeedsDisplay()</pre><p>won’t change that attribute.</p><p>UIKit has no reason to rewrite an existing NSAttributedString just because the surrounding interface changed direction.</p><p>One possible solution is:</p><pre>paragraphStyle.alignment = .natural</pre><p>But there’s a subtle distinction here.</p><p>Natural text alignment follows the natural writing direction of the text.</p><p>An English string inside an Arabic interface may still be aligned to the left.</p><p>Sometimes that’s exactly what you want.</p><p>Sometimes it isn’t.</p><p>If the design requires alignment relative to the interface rather than the text’s writing direction, you need to choose it explicitly:</p><pre>func alignment(isRTL: Bool) -&gt; NSTextAlignment {<br>    isRTL ? .right : .left<br>}</pre><p>And rebuild the affected attributed strings when the language changes.</p><p>The same issue appears with cached images, directional icons, and other presentation properties calculated during initialization.</p><p>The view hierarchy may have the correct direction while its content still reflects an earlier state.</p><h3>UITextField: Where Things Get Even More Interesting</h3><p>Text fields introduce another layer of complexity.</p><p>Let’s configure one for RTL:</p><pre>textField.semanticContentAttribute =<br>    .forceRightToLeft</pre><pre>textField.textAlignment = .right</pre><p>With Arabic text, this may look perfectly reasonable.</p><p>Now try typing an English name.</p><p>Or a phone number.</p><p>Or a sentence containing Arabic words, Latin characters, punctuation, and numbers.</p><p>Suddenly, the relationship between layout direction and text direction becomes much less obvious.</p><p>There are three separate concepts involved:</p><ul><li>The direction of the interface.</li><li>The alignment of the text.</li><li>The writing direction used to display the characters.</li></ul><p>The last one involves the Unicode Bidirectional Algorithm.</p><p>Latin text generally retains its left-to-right ordering even when embedded in an Arabic sentence.</p><p>Caret placement, selection behavior, and punctuation can also depend on the surrounding text.</p><p>UIKit provides APIs for controlling base writing direction:</p><pre>textField.setBaseWritingDirection(<br>    .rightToLeft,<br>    for: .all<br>)</pre><p>But forcing RTL writing direction everywhere isn’t a reliable solution for every input type.</p><p>A phone number may need to preserve its familiar numeric representation.</p><p>A free-form text field may need to follow the content.</p><p>A username field may need entirely different behavior.</p><p>This is why I wouldn’t apply .forceRightToLeft to every text field globally and assume the problem is solved.</p><p>Each input type needs an explicit decision about its expected behavior.</p><h3>The Back Button That Refused to Turn Around</h3><p>Navigation introduces another interesting case.</p><p>Imagine a UINavigationBar that has already adapted to RTL.</p><p>The buttons are in the expected positions.</p><p>The title looks correct.</p><p>But the custom back arrow still points left.</p><p>A common reason is a custom image configured through:</p><pre>navigationBar.setBackIndicatorImage(<br>    image,<br>    transitionMaskImage: image<br>)</pre><p>UIKit supports RTL-aware navigation, but an arbitrary image doesn’t automatically communicate how it should behave when the interface direction changes.</p><p>Whenever possible, I prefer system navigation behavior.</p><p>For custom controls, directional SF Symbols are a useful starting point:</p><pre>UIImage(systemName: &quot;chevron.backward&quot;)</pre><p>Custom assets may require explicit support for RTL mirroring.</p><p>But blindly flipping every image is another trap.</p><p>Logos, photographs, and many non-directional illustrations shouldn’t be mirrored.</p><p>So even here, the correct solution depends on the meaning of the content.</p><h3>Gestures Don’t Care About Your Localization</h3><p>Now consider a card that users can swipe left to dismiss.</p><p>The gesture handler might look like this:</p><pre>let translation = gesture.translation(in: view)</pre><pre>if translation.x &lt; 0 {<br>    dismissCard()<br>}</pre><p>Switch the application to Arabic.</p><p>The interface may be mirrored, but UIPanGestureRecognizer still reports movement in the view’s coordinate system.</p><p>A negative horizontal translation still represents movement to the left.</p><p>If the interaction is supposed to follow the logical direction of the interface, the gesture logic needs to account for RTL explicitly.</p><p>For example:</p><pre>func logicalTranslation(<br>    _ value: CGFloat,<br>    isRTL: Bool<br>) -&gt; CGFloat {<br>    value * (isRTL ? -1 : 1)<br>}</pre><p>The rest of the interaction can then operate on normalized coordinates.</p><p>But the same normalization must be applied consistently to translation, velocity, and completion conditions.</p><p>Otherwise, a card might move in the expected direction while the dismissal threshold behaves as if the interface were still LTR.</p><p>And not every gesture should be mirrored.</p><p>Some interactions are tied to physical directions rather than reading order.</p><p>Again, UIKit can’t make that product decision for us.</p><h3>What If We Just Rebuild Everything?</h3><p>After dealing with enough of these issues, a tempting idea appears.</p><p>Instead of updating every existing component, why not recreate the interface after the language changes?</p><p>Something like:</p><pre>func rebuildInterface(<br>    window: UIWindow,<br>    direction: UISemanticContentAttribute<br>) {<br>    window.semanticContentAttribute = direction</pre><pre>    let rootController = makeRootController()</pre><pre>    rootController.view.semanticContentAttribute =<br>        direction</pre><pre>    window.rootViewController = rootController<br>}</pre><p>Here, makeRootController() represents an application-specific factory.</p><p>The advantage is obvious.</p><p>Newly created components can initialize using the selected language and direction.</p><p>Attributed strings can be rebuilt. Images can be selected again. Cached presentation properties can be recalculated.</p><p>This avoids some of the complexity of updating an existing hierarchy.</p><p>But there’s a catch.</p><p>Imagine the user is four screens deep in a navigation flow, halfway through filling out a form.</p><p>Replacing the root view controller can destroy that UI state.</p><p>To make this approach usable, the application needs a way to preserve and restore navigation, form data, scroll positions, and any other relevant state.</p><p>There’s another limitation.</p><p>Rebuilding the root controller doesn’t recreate the UIWindowScene or guarantee a change to its layout-direction traits.</p><p>So this approach can solve stale component state without necessarily resolving every difference between semantic direction and the system environment.</p><p>It’s a practical option in some architectures, but not a universal fix.</p><h3>Why I Would Avoid Global Method Swizzling</h3><p>At some point, it’s tempting to intercept UIKit’s lifecycle methods and apply the desired direction automatically.</p><p>For example, by swizzling layoutSubviews().</p><p>The idea sounds convenient: every view eventually participates in layout, so why not enforce RTL there?</p><p>Because layoutSubviews() can be called repeatedly during ordinary UI updates.</p><p>Changing layout-affecting properties inside it may trigger additional layout work.</p><p>And even if the implementation avoids those problems, it still doesn’t automatically rebuild attributed strings, update cached images, or correct custom gesture logic.</p><p>We would be introducing global runtime behavior without actually addressing the main source of inconsistency.</p><p>For this problem, I wouldn’t use method swizzling as the foundation of the localization system.</p><h3>The Actual Solution: Stop Treating RTL as a Global Switch</h3><p>By this point, a pattern becomes clear.</p><p>The troublesome components have something in common.</p><p>They depend on layout direction, but they don’t necessarily update that dependency when the direction changes.</p><p>Some read effectiveUserInterfaceLayoutDirection.</p><p>Others read traitCollection.layoutDirection.</p><p>Others calculate a Boolean once during initialization and never revisit it.</p><p>Trying to force UIKit to synchronize all of those decisions through a single property isn’t reliable.</p><p>Instead, I would make the application’s selected language and direction explicit state.</p><p>For example:</p><pre>enum LayoutDirection {<br>    case leftToRight<br>    case rightToLeft</pre><pre>    var semanticAttribute: UISemanticContentAttribute {<br>        switch self {<br>        case .leftToRight:<br>            return .forceLeftToRight</pre><pre>        case .rightToLeft:<br>            return .forceRightToLeft<br>        }<br>    }<br>}</pre><p>When the user changes the language, the localization service updates that state and notifies the relevant parts of the application.</p><p>The application then applies the new semantic direction to its windows and refreshes components whose content depends on the language or direction.</p><p>For simple views, UIKit’s automatic behavior may be sufficient.</p><p>For attributed text, custom images, and gesture handling, explicit updates may be required.</p><p>For more complex screens, rebuilding part of the interface may be the cleaner option.</p><p>The important part is making those decisions intentionally rather than hoping that another call to layoutIfNeeded() will fix everything.</p><h3>Test the Transition, Not Just the Destination</h3><p>One final lesson: launching directly into Arabic isn’t enough to validate runtime RTL support.</p><p>During a cold launch, components can initialize with the correct direction from the beginning.</p><p>Runtime switching is a different scenario.</p><p>At minimum, I would test:</p><pre>Cold Launch → LTR<br>Cold Launch → RTL</pre><pre>LTR → RTL<br>RTL → LTR</pre><pre>LTR → RTL → LTR<br>RTL → LTR → RTL</pre><p>The repeated transitions are especially useful.</p><p>They expose components that can switch to RTL once but fail to restore their original state.</p><p>I’d also test open modal screens, navigation stacks, mixed-language text fields, and custom gestures.</p><p>When something behaves unexpectedly, these three values are a useful starting point:</p><pre>view.effectiveUserInterfaceLayoutDirection</pre><pre>view.traitCollection.layoutDirection</pre><pre>window.windowScene?<br>    .traitCollection<br>    .layoutDirection</pre><p>If they differ, the next question is which one the problematic component actually uses.</p><p>That often tells you where to investigate.</p><h3>Five Minutes Later…</h3><p>I started this task looking for a way to switch an entire UIKit application to RTL with a single operation.</p><p>First, I tried changing semanticContentAttribute.</p><p>Then I tried forcing layout updates.</p><p>Then I looked at trait collections, rebuilding the interface, and the possibility of intercepting UIKit lifecycle methods.</p><p>Each approach addressed part of the problem.</p><p>None of them solved every case.</p><p>The most useful discovery was understanding why.</p><p>UIKit exposes multiple mechanisms related to layout direction, while application components can maintain their own direction-dependent state.</p><p>Those mechanisms don’t necessarily update together when the user changes the language at runtime.</p><p>Once I understood that, RTL bugs became much easier to investigate.</p><p>Instead of immediately adding another .forceRightToLeft, I started asking two questions:</p><p><strong>Where does this component get its layout direction?</strong></p><p><strong>And when does it calculate the values that depend on it?</strong></p><p>Those two questions have been more useful than any global RTL workaround.</p><p>So yes, switching LTR to RTL at runtime sounded like a five-minute adventure.</p><p>Rick was right about one thing.</p><p>We definitely went in.</p><p>Getting out took considerably longer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55a38932931f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>