Last active
November 16, 2024 19:17
-
-
Save joethephish/7632b238ffe805ed074d72a1462a4ad0 to your computer and use it in GitHub Desktop.
Sample code for how to highlight text within a TextField in SwiftUI in my app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
TextField(placeholder, text:$event.title, axis: Axis.vertical) | |
.keyboardType(.default) | |
.focused($textFieldFocus, equals:controlId) | |
// When newline is detected, create a new item (or delete if it's empty) | |
// We'd do this in onKeyPress(.return) but that's only for hardware keyboards | |
.lineLimit(100, reservesSpace: false) | |
.overlay(alignment: Alignment(horizontal:.leading, vertical: .center)) { | |
GeometryReader { proxy in | |
if focussed.control == controlId, let timeRanges = tools.scannedTiming?.ranges { | |
// The series of spaces is to get around the line break strategy that SwiftUI doens't give us control over | |
// https://stackoverflow.com/questions/72685881/swiftui-text-doesnt-fit-full-width-while-having-multiple-lines | |
// The line break strategy on TextField is different to Text. On Text it tries to avoid having orphan words | |
// by having more than word fall down a line even if there's space for another above. By adding extra whitespace | |
// on the end, it prevents it doing this. | |
// Oh dear god of hacks this is my offering. | |
Text(attributedTitle(title:event.title+" ", highlightedRanges:timeRanges, color:.accentColor)) | |
.frame(width:proxy.size.width, alignment: .leading) | |
.foregroundStyle(.clear) // to debug, .red and add .border(.red) | |
.allowsHitTesting(false) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment