Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.

Posts under General subtopic

Post

Replies

Boosts

Views

Activity

How can we performantly scroll to a target location using TextKit 2?
How can we performantly scroll to a target location using TextKit 2? Hi everyone, I'm building a custom text editor using TextKit 2 and would like to scroll to a target location efficiently. For instance, I would like to move to the end of a document seamlessly, similar to how users can do in standard text editors by using CMD + Down. Background: NSTextView and TextEdit on macOS can navigate to the end of large documents in milliseconds. However, after reading the documentation and experimenting with various ideas using TextKit 2's APIs, it's not clear how third-party developers are supposed to achieve this. My Code: Here's the code I use to move the selection to the end of the document and scroll the viewport to reveal the selection. override func moveToEndOfDocument(_ sender: Any?) { textLayoutManager.ensureLayout(for: textLayoutManager.documentRange) let targetLocation = textLayoutManager.documentRange.endLocation let beforeTargetLocation = textLayoutManager.location(targetLocation, offsetBy: -1)! textLayoutManager.textViewportLayoutController.layoutViewport() guard let textLayoutFragment = textLayoutManager.textLayoutFragment(for: beforeTargetLocation) else { return } guard let textLineFragment = textLayoutFragment.textLineFragment(for: targetLocation, isUpstreamAffinity: true) else { return } let lineFrame = textLayoutFragment.layoutFragmentFrame let lineFragmentFrame = textLineFragment.typographicBounds.offsetBy(dx: 0, dy: lineFrame.minY) scrollToVisible(lineFragmentFrame) } While this code works as intended, it is very inefficient because ensureLayout(_:) is incredibly expensive and can take seconds for large documents. Issues Encountered: In my attempts, I have come across the following two issues. Estimated Frames: The frames of NSTextLayoutFragment and NSTextLineFragment are approximate and not precise enough for scrolling unless the text layout fragment has been fully laid out. Laying out all text is expensive: The frames become accurate once NSTextLayoutManager's ensureLayout(for:) method has been called with a range covering the entire document. However, ensureLayout(for:) is resource-intensive and can take seconds for large documents. NSTextView, on the other hand, accomplishes the same scrolling to the end of a document in milliseconds. I've tried using NSTextViewportLayoutController's relocateViewport(to:) without success. It's unclear to me whether this function is intended for a use case like mine. If it is, I would appreciate some guidance on its proper usage. Configuration: I'm testing on macOS Sonoma 14.5 (23F79), Swift (AppKit), Xcode 15.4 (15F31d). I'm working on a multi-platform project written in AppKit and UIKit, so I'm looking for either a single solution that works in both AppKit and UIKit or two solutions, one for each UI framework. Question: How can third-party developers scroll to a target location, specifically the end of a document, performantly using TextKit 2? Steps to Reproduce: The issue can be reproduced using the example project (download from link below) by following these steps: Open the example project. Run the example app on a Mac. The example app shows an uneditable text view in a scroll view. The text view displays a long text. Press the "Move to End of Document" toolbar item. Notice that the text view has scrolled to the bottom, but this took several seconds (~3 seconds on my MacBook Pro 16-inch, 2021). The duration will be shown in Xcode's log. You can open the ExampleTextView.swift file and find the implementation of moveToEndOfDocument(_:). Comment out line 84 where the ensureLayout(_:) is called, rerun the app, and then select "Move to End of Document" again. This time, you will notice that the text view moves fast but does not end up at the bottom of the document. You may also open the large-file.json in the project, the same file that the example app displays, in TextEdit, and press CMD+Down to move to the end of the document. Notice that TextEdit does this in mere milliseconds. Example Project: The example project is located on GitHub: https://github.com/simonbs/apple-developer-forums/tree/main/how-can-we-performantly-scroll-to-a-target-location-using-textkit-2 Any advice or guidance on how to achieve this with TextKit 2 would be greatly appreciated. Thanks in advance! Best regards, Simon
10
9
2.2k
4h
What is the scroll edge effect supposed to look like now?
At WWDC the scroll edge effect was presented as a variable blur combined with a soft gradient. Since beta 4 the bottom scroll edge effect has no blur, the top bar sometimes has, but sometimes does not. Even in my own app I have two views with totally different results. This was not changed back in beta 5, so I assume this is not a bug but an intended change. It's hard to design for such a moving target. Especially the missing bottom blur looks bad in a lot of places in my app and I'm debating not shipping the new design if this does not get resolved. Is there any guidance how this effect is supposed to look now? At this point it just seems random and there's no way adjust the way it looks. Phone: Top blur, bottom no blur Settings: Top blur, bottom no blur Notes: No blur at all Music: No blur at all My own app: No top blur My own app: Top blur
3
0
87
6h
The PKCanvasView Created by PDFPageOverlayViewProvider cannot work normally
By setting the PKCanvasView background color to blue, I can tell that the PKCanvasView for each PDFPage is created normally, but it does not respond to touch. Specifically, whether it is finger or applepencil, all the responses of the page occur from PDFView(such as zoom and scroll), and PKCanvasView can not draw, please how to solve? class PDFAnnotatableViewController: UIViewController, PDFViewDelegate { private let pdfView = PDFView() private var pdfDocument: PDFDocument? let file: FileItem private var userSettings: UserSettings @Binding var selectedPage: Int @Binding var currentMode: Mode @Binding var latestPdfChatResponse: LatestPDFChatResponse @State private var pdfPageCoordinator = PDFPageCoordinator() @ObservedObject var userMessage: ChatMessage init(file: FileItem, userSettings: UserSettings, drawDataList: Binding<[DrawDataItem]>, selectedPage: Binding<Int>, currentMode: Binding<Mode>, latestPdfChatResponse: Binding<LatestPDFChatResponse>, userMessage: ChatMessage) { self.file = file self.userSettings = userSettings self._selectedPage = selectedPage self._currentMode = currentMode self._latestPdfChatResponse = latestPdfChatResponse self.userMessage = userMessage super.init(nibName: nil, bundle: nil) DispatchQueue.global(qos: .userInitiated).async { if let document = PDFDocument(url: file.pdfLocalUrl) { DispatchQueue.main.async { self.pdfDocument = document self.pdfView.document = document self.goToPage(selectedPage: selectedPage.wrappedValue - 1) } } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupPDFView() } private func setupPDFView() { pdfView.delegate = self pdfView.autoScales = true pdfView.displayMode = .singlePage pdfView.displayDirection = .vertical pdfView.backgroundColor = .white pdfView.usePageViewController(true) pdfView.displaysPageBreaks = false pdfView.displaysAsBook = false pdfView.minScaleFactor = 0.8 pdfView.maxScaleFactor = 3.5 pdfView.pageOverlayViewProvider = pdfPageCoordinator if let document = pdfDocument { pdfView.document = document goToPage(selectedPage: selectedPage) } pdfView.frame = view.bounds pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(pdfView) NotificationCenter.default.addObserver( self, selector: #selector(handlePageChange), name: .PDFViewPageChanged, object: pdfView ) } // Dealing with page turning @objc private func handlePageChange(notification: Notification) { guard let currentPage = pdfView.currentPage, let document = pdfView.document else { return } let currentPageIndex = document.index(for: currentPage) if currentPageIndex != selectedPage - 1 { DispatchQueue.main.async { self.selectedPage = currentPageIndex + 1 } } } func goToPage(selectedPage: Int) { guard let document = pdfView.document else { return } if let page = document.page(at: selectedPage) { pdfView.go(to: page) } } // Switch function func togglecurrentMode(currentMode: Mode){ DispatchQueue.main.async { if self.currentMode == .none{ self.pdfView.usePageViewController(true) self.pdfView.isUserInteractionEnabled = true } else if self.currentMode == .annotation { if let page = self.pdfView.currentPage { if let canvasView = self.pdfPageCoordinator.getCanvasView(forPage: page) { canvasView.isUserInteractionEnabled = true canvasView.tool = PKInkingTool(.pen, color: .red, width: 20) canvasView.drawingPolicy = .anyInput canvasView.setNeedsDisplay() } } } } } } class MyPDFPage: PDFPage { var drawing: PKDrawing? func setDrawing(_ drawing: PKDrawing) { self.drawing = drawing } func getDrawing() -> PKDrawing? { return self.drawing } } class PDFPageCoordinator: NSObject, PDFPageOverlayViewProvider { var pageToViewMapping = [PDFPage: PKCanvasView]() func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? { var resultView: PKCanvasView? = nil if let overlayView = pageToViewMapping[page] { resultView = overlayView } else { let canvasView = PKCanvasView(frame: view.bounds) canvasView.drawingPolicy = .anyInput canvasView.tool = PKInkingTool(.pen, color: .systemYellow, width: 20) canvasView.backgroundColor = .blue pageToViewMapping[page] = canvasView resultView = canvasView } if let page = page as? MyPDFPage, let drawing = page.drawing { resultView?.drawing = drawing } return resultView } func pdfView(_ pdfView: PDFView, willEndDisplayingOverlayView overlayView: UIView, for page: PDFPage) { guard let overlayView = overlayView as? PKCanvasView, let page = page as? MyPDFPage else { return } page.drawing = overlayView.drawing pageToViewMapping.removeValue(forKey: page) } func savePDFDocument(_ pdfDocument: PDFDocument) -> Data { for i in 0..<pdfDocument.pageCount { if let page = pdfDocument.page(at: i) as? MyPDFPage, let drawing = page.drawing { let newAnnotation = PDFAnnotation(bounds: drawing.bounds, forType: .stamp, withProperties: nil) let codedData = try! NSKeyedArchiver.archivedData(withRootObject: drawing, requiringSecureCoding: true) newAnnotation.setValue(codedData, forAnnotationKey: PDFAnnotationKey(rawValue: "drawingData")) page.addAnnotation(newAnnotation) } } let options = [PDFDocumentWriteOption.burnInAnnotationsOption: true] if let resultData = pdfDocument.dataRepresentation(options: options) { return resultData } return Data() } func getCanvasView(forPage page: PDFPage) -> PKCanvasView? { return pageToViewMapping[page] } } Is there an error in my code? Please tell me how to make PKCanvasView painting normally?
1
0
356
6d
Quick Look Extension does not load MapKit map properly anymore, after macOS Sequoia
It appears that starting with macOS Sequoia, Quick Look Preview extension no longer loads MapKit maps correctly anymore. Map tiles do not appear, leaving users with a beige background. Users report that polylines do render correctly, but annotations appears black. This was previously working fine in prior macOS versions including Sonoma. STEPS TO REPRODUCE Create a macOS app project, with an associated document. Ensure project has a Quick Look preview extension, with necessary basic setups. Ensure that the extension mentioned in (2) must have a MKMapView. Any other cosmetic changes, etc, does not need to be implemented to observe the base issue. Do note that it has been reported that in addition to the map tiles not loading, annotations don't render correctly as well.
2
2
760
6d
Allow iOS Arabic keyboard to support custom developer tools
Hello Apple Developer Team, I kindly ask if you could allow developers to access the same Arabic keyboard used in iOS — with the exact layout, design, and smooth performance as the default iPhone keyboard. Currently, building a custom Arabic keyboard that replicates Apple’s layout results in severe lag and a frustrating user experience. Despite many attempts, it’s nearly impossible to match the original keyboard’s speed, size, and feel — especially for Arabic. I fully understand your security concerns. To ensure safety, Apple could prevent typing in password fields and clearly mark the keyboard as customized (e.g., a red Send button). That would be completely acceptable. I am not planning to publish anything on the App Store. This is purely for personal use only — to play and experiment with friends on platforms like Discord, by adding simple tools like repeating each word twice or splitting typed words into separate letters. Honestly, I am mentally exhausted from trying to rebuild something that already exists. Every attempt leads to slow performance and disappointment. I just want the real keyboard — the same one we already use — and the ability to build basic features on top of it. Thank you very much for your time and understanding. Best regards, Abdullah Abdulrahman Aljurayyad
1
0
63
1w
Insight into BaseBoard/FrontBoardServices Crashes Needed
We're seeing a sharp uptick in BaseBoard/FrontBoardServices crashes since we migrated from UIApplicationDelegate to UIWindowSceneDelegate. Having exhausted everything on my end short of reverse engineering BaseBoard or making changes without being able to know if they work, I need help. I think all I need to get unstuck is an answer to these questions, if possible: What does -[BSSettings initWithSettings:] enumerate over? If I know what's being enumerated, I'll know what to look for in our app. What triggers FrontBoardServices to do this update? If I can reproduce the crash--or at least better understand when it may happen--I will be better able to fix it Here's two similar stack traces: App_(iOS)-crashreport-07-30-2025_1040-0600-redacted.crash App_(iOS)-crashreport-07-30-2025_1045-0600-redacted.crash Since these are private trameworks, there is no documentation or information on their behavior that I can find. There are other forum posts regarding this crash, on here and on other sites. However, I did not find any that shed any insight on the cause or conditions of the crash. Additionally, this is on iPhone, not macOS, and not iPad. This post is different, because I'm asking specific questions that can be answered by someone with familiarity on how these internal frameworks work. I'm not asking for help debugging my application, though I'd gladly take any suggestions/tips! Here's the long version, in case anyone finds it useful: In our application, we have seen a sharp rise in crashes in BaseBoard and FrontBoardServices, which are internal iOS frameworks, since we migrated our app to use UIWindowSceneDelegate. We were using exclusively UIApplicationDelegate before. The stack traces haven't proven very useful yet, because we haven't been able to reproduce the crashes ourselves. Upon searching online, we have learned that Baseboard/Frontsoardservices are probably copying scene settings upon something in the scene changing. Based on our crash reports, we know that most of our users are on an iPhone, not an iPad or macOS, so we can rule out split screen or window resizing. Our app is locked to portrait as well, so we can also rule out orientation changes. And considering the stack trace is in the middle of an objc_retain_x2 call, which is itself inside of a collection enumeration, we are assuming that whatever is being enumerated probably was changed or deallocated during enumeration. Sometimes it's objc_retain_x2, and sometimes it's a release call. And sometimes it's a completely different stack trace, but still within BaseBoard/FrontBoardServices. I suspect these all share the same cause. Because it's thread 0 that crashed, we know that BaseBoard/FrontBoardServices were running on the main thread, which means that for this crash to occur, something might be changing on a background thread. This is what leads me to suspect a race condition. There are many places in our app where we accidentally update the UI from a background thread. We've fixed many of them, but I'm sure there are more. Our app is large. Because of this, I think background UI are the most likely cause. However, since I can't reproduce the crash, and because none of our stack traces clearly show UI updates happening on another thread at the same time, I am not certain. And here's the stack trace inline, in case the attachments expire or search engines can't read them: Thread 0 name: Thread 0 Crashed: objc_retain_x2 (libobjc.A.dylib) BSIntegerMapEnumerateWithBlock (BaseBoard) -[BSSettings initWithSettings:] (BaseBoard) -[BSKeyedSettings initWithSettings:] (BaseBoard) -[FBSSettings _settings:] (FrontBoardServices) -[FBSSettings _settings] (FrontBoardServices) -[FBSSettingsDiff applyToMutableSettings:] (FrontBoardServices) -[FBSSettingsDiff settingsByApplyingToMutableCopyOfSettings:] (FrontBoardServices) -[FBSSceneSettingsDiff settingsByApplyingToMutableCopyOfSettings:] (FrontBoardServices) -[FBSScene updater:didUpdateSettings:withDiff:transitionContext:completion:] (FrontBoardServices) __94-[FBSWorkspaceScenesClient _queue_updateScene:withSettings:diff:transitionContext:completion:]_block_invoke_2 (FrontBoardServices) -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] (FrontBoardServices) __94-[FBSWorkspaceScenesClient _queue_updateScene:withSettings:diff:transitionContext:completion:]_block_invoke.cold.1 (FrontBoardServices) __94-[FBSWorkspaceScenesClient _queue_updateScene:withSettings:diff:transitionContext:completion:]_block_invoke (FrontBoardServices) _dispatch_client_callout (libdispatch.dylib) _dispatch_block_invoke_direct (libdispatch.dylib) __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ (FrontBoardServices) -[FBSMainRunLoopSerialQueue _targetQueue_performNextIfPossible] (FrontBoardServices) -[FBSMainRunLoopSerialQueue _performNextFromRunLoopSource] (FrontBoardServices) __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ (CoreFoundation) __CFRunLoopDoSource0 (CoreFoundation) __CFRunLoopDoSources0 (CoreFoundation) __CFRunLoopRun (CoreFoundation) CFRunLoopRunSpecific (CoreFoundation) GSEventRunModal (GraphicsServices) -[UIApplication _run] (UIKitCore) UIApplicationMain (UIKitCore) (null) (UIKitCore) main (AppDelegate.swift:0) 0x1ab8cbf08 + 0
Topic: UI Frameworks SubTopic: General Tags:
3
4
91
1w
How to keep bottom toolbar pinned, when sheet's detent are changed in code
I am trying to add a pinned(always visible and not moving) toolbar to the bottom of UISheetPresentationController or presentationDetent. This is achievable when the user is dragging to change the size of the sheet. But when changing the detent by code, it does not work. For example, when changing from medium to large, the ViewController's size is changed to large then moved up to the position. From the user's POV, anything at the bottom to disappear for a few frames then reappears. From my testing, when using UISheetPresentationController, ViewController only knows the medium and large state's frame and bounds, so manually setting it up won't work. Is there a way to keep views at the bottom always visible in this case? The sample code below is in SwiftUI for easy recreation, and the responses can be in UIKit. Sample Code: struct ContentView: View { @State var showSheet: Bool = true @State var detent: PresentationDetent = .medium var body: some View { EmptyView() .sheet(isPresented: $showSheet) { ScrollView { } .safeAreaInset(edge: .bottom) { Button { detent = (detent == .medium) ? .large : .medium } label: { Text("Change Size") } .buttonStyle(.borderedProminent) .presentationDetents([.medium, .large], selection: $detent) .presentationBackgroundInteraction(.enabled) } } } }
1
0
71
1w
Multitasking & Gestures >> Seeing the app icon instead of contact info when drag-and-dropping contacts into my Calendar view in iOS 26.0 Beta?
Multitasking & Gestures >> Seeing the app icon instead of contact info when drag-and-dropping contacts into my Calendar view in iOS 26.0 Beta? In Settings Multitasking & Gestures >> Select Full-screen Apps then worked fine. But when Multitasking & Gestures >> select Windowed Apps then any suggestion how to handle on app development for one or two screen?
Topic: UI Frameworks SubTopic: General
2
0
67
1w
Can I add "com.apple.developer.calling-app" in the InHouse account?
https://developer.apple.com/documentation/callkit/preparing-your-app-to-be-the-default-calling-app I have 2 accounts, one for App store and one for tesing (Inhouse type). I added the capability in the Xcode project, and can run it. But when I run a Inhouse build for it on my CI server, it failed. So is the Inhouse build support this "com.apple.developer.calling-app"?
1
0
50
1w
Change the Language of my current input keyboard programmatically in iOS and MacOS
We are building a Multi-Lingual Business Application -- where the user is able to enter values and data in multiple languages. One of our main use cases is, if a user is editing or adding to a text value or data that is in a different language. For example, the data they are editing could be in Japanese, and the user's current input language is set to English, then when they enter the editing mode, the input language is automatically set to Japanese by us -- programmatically. They can go back to editing English items, and the input language is changed back to English, and similarly, when they come back to edit the Japanese data or some German data, then the input language is again automatically changed to the respective language by the application -- without causing the user to manually go to the settings and change it. Is there any current way to have this behaviour in MacOS and iOS now? Please suggest what can be done to achieve the same.
4
1
576
1w
Context menus need option to disable morphing
For some controls it is desirable to not use the morphing transition when presenting a Menu. Instead, you might want to have the old behavior, where the menu is presented above or below the initiating view. This can be the case for any other control than toolbar items, but especially for bigger content cards, that should trigger a menu upon tapping it once. In those cases it looks weird and does not really help to keep context of what the action is doing. Is there some way to do this right now? In case it's not, I also filed a feedback. FB18413055
0
0
53
2w
What to do about the new glass medium detent sheets
So many issues with the new sheet design, I don't think I can ship these. And it's both in UIKit and SwiftUI. Honestly these net sheets seem like a failure from start to finish and I don't believe it will get better for the initial release. Toolbar buttons in medium detent size have very low contrast and look bad with their opaque appearance During the transition from medium to large detent the whole sheet flickers and turns transparent for a split moment, creating a very jarring transition (video here: https://mastodon.social/@nicoreese/114938826906689965). In the large detent the background is always white in light mode making the cells bleed into the background making them indistinguishable from it. I should be able to set a background color for the large detent which smoothly transitions to it. Like: glass in medium and system grouped background in large. Any interaction with the medium detent sheet makes it scale up. Why? It's okay for single interactions but not for when the user taps something in it rapidly. There needs to be a way to disable this behavior. In the medium detent List/UICollectionView rows are white in light mode or gray in dark mode. Especially in dark mode it looks very bad against the glass background. Those rows should probably be translucent to better fit the glass. This needs serious fixing and fast. FB18919680 FB18919657 FB18919600 FB18919549 FB18919496 FB18919630
0
1
73
2w
WKApplication、WKWatchKitApp
Validation failed Missing Info.plist value. A value for the key “WKApplication”, or “WKWatchKitApp” if your project has a WatchKit App Extension target, is required in “demo.app/demo.app” bundle. For details, see: https://developer.apple.com/documentation/watchkit/creating_independent_watchos_apps/setting_up_a_watchos_project (ID: 1***fc8) 我们APP中没有watchkit相关功能,但是在xcode16.3上传包的时候一直提示此错误?是什么原因?
3
1
84
2w
UWB Background Ranging with Live Activities - iOS 18.4
I’m developing an app that uses UWB for proximity detection between users. I have questions about iOS 18.4’s new Live Activity background UWB capabilities. Live Activity Background UWB “Loophole” Apple’s documentation states that apps can continue UWB ranging in background with “any supported device” if a Live Activity is started as the app backgrounds - without requiring Bluetooth LE pairing. Key Questions: 1. Background initiation: Can new UWB sessions be initiated between devices while in background using Live Activities, or must sessions start in foreground first? 2. No pairing requirement: Does this iOS 18.4 Live Activity approach truly eliminate the need for Bluetooth LE pairing for background UWB ranging? 3. Session persistence: How long can UWB ranging continue in background with an active Live Activity? 4. Testing without entitlement: Can I test UWB functionality between multiple devices in Xcode without the Nearby Interaction entitlement approved yet? Context My app needs precise proximity detection between users in real-time. The Live Activity background capability would be essential since users need to put phones away while the ranging continues. This iOS 18.4 feature seems like it could be a game-changer for apps requiring background UWB functionality without the complexity of Bluetooth pairing. Has anyone successfully implemented this Live Activity + background UWB approach?
0
0
157
2w
Replacement for deprecated CLPlacemark.region?
Hello, I use CLGeocoder to get the CLLocationCoordinate2D and CLRegion for an address. Now that this is deprecated in OS 26, I don't see a replacement for that property on MKMapItem via MKMapItemRequest and PlaceDescriptor. I've filed FB19027378 on this issue. Basically I have some addresses that have a street address, and others that just have a city. With CLGeocoder, when geocoding just the city, the CLRegion was set such that I could show my map zoomed out just right. I'm not sure how to do that now. Thanks!
0
0
71
2w
Alternative icons with Icon Composer
Hello dear Apple Engineers and fellow developers. Today I was crafting my new App Icon with Icon Composer and I was wondering how I can support alternative App Icons. I couldn't find any documentation about it yet. Is it already supported? Will it be supported soon?
Topic: UI Frameworks SubTopic: General
3
0
106
2w
Best Option for Programmatically Scrolling Long Dynamic Text
Hello! I am trying to create an iOS app that is based around a very large, vertically scrolling text view. The text is broken up into many sections, and the user should be able to press buttons in the navigation, which programmatically scroll to those sections. The user can also change the font size in a settings menu. It should generally keep the user's spot when resizing fonts or rotating the screen (from portrait to landscape). The problem I've been having is that no method of lazy text loading allows accurate enough navigation, and the text is too long to calculate the whole UI all at once. Here's my process in trying to find a solution: My app is built in SwiftUI, so I started with a ScrollView and a LazyVStack, and I used .scrollPosition() and bound it to an Int?. It worked pretty well for most scroll locations both on screen and far off the screen, but when I programmatically scroll to a location that is off the screen but not very far off, it completely misses. So, I investigated UIKit, and found that UITextView was a much better fit for the way I wanted to present the long text. I could also programmatically navigate by storing the NSRange of each section. I tried to use scrollRangeToVisible(), but for long distance it would scroll so that the desired section was just below the viewport and thus off screen. Then I tried to use UITextView's textLayoutManager.textViewportLayoutController.relocateViewport() to send it to the correct NSTextRange, it would not jump all the way, but instead would do nothing until I tried to scroll again and it would jump slightly forward. I tried to use textViewportLayoutController.layoutViewport() after the jump, and that fixed the glitch when scrolling, but it still did not jump to the correct place, only slightly forward. Then, I looked into TextKit 2 and the way it worked to try to find a solution. From what I can tell, it seems that to affect the NSTextViewportLayoutController without having to rewrite it, I need an NSTextViewportLayoutControllerDelegate, but the delegate required me to manually lay out the views, and in all the examples I've seen that use a custom NSTextViewportLayoutControllerDelegate, they wrote their own custom text view instead of using the default UITextView. I started looking into writing a custom text view so I can get the programmatic scroll to work consistently. However, it felt like, from a maintainability standpoint, it would probably be best to stick with what Apple has already implemented. For now, I found a workaround that scrolls consistently. Here is the code: if let start = self.textView.position(from: self.textView.beginningOfDocument, offset: desiredLineRange.location) { let location = textView.caretRect(for: start) self.textView.setContentOffset(CGPoint(x: 0, y: location.origin.y), animated: false) } if let start = self.textView.position(from: self.textView.beginningOfDocument, offset: desiredLineRange.location) { let location = textView.caretRect(for: start) self.textView.setContentOffset(CGPoint(x: 0, y: location.origin.y), animated: false) } It does the job, because the first time it gets close enough, and the second time it gets to the precise location, but it just feels like a bit of a hack to run the same code twice. I was wondering if anyone knows what I could be doing wrong and if Apple provides any solutions for this? (Also, all my UIKit navigation attempts ran inside an @objc func, which I passed using button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside). Just so you know in case it may be a problem with the way Swift and UIKit handle concurrency/parallel tasks). Thank you!
0
0
133
3w