Construct and manage graphical, event-driven user interfaces for iOS or tvOS apps using UIKit.

UIKit Documentation

Post

Replies

Boosts

Views

Activity

UIKit Document App -- adding a toolbar
I've had to ditch the SwiftUI app lifecycle due to this issue: https://developer.apple.com/forums/thread/742580 After creating a new UIKit document app as a test, it doesn't have a toolbar when opening the document. How can I add one along the lines of https://developer.apple.com/wwdc22/10069 ? The UIDocumentViewController isn't already embedded in a UINavigationController it seems. To reproduce: New Project -> iOS -> Document App. Select Interface: Storyboard. Add an empty "untitled.txt" resource to the project. Change the first line in documentBrowser(_:,didRequestDocumentCreationWithHandler:) to let newDocumentURL: URL? = Bundle.main.url(forResource: "untitled", withExtension: "txt")
2
0
505
Dec ’23
Why UIActivityViewController navigationBar backgroundColor is clear?
Under iOS 17, I need to set view.backgroundColor when using UIActivityViewController, otherwise the navigationBar will be transparent. (iOS 17 does not have this problem) I have checked many tutorial examples but this situation is not mentioned. Is there any implementation missing from my code? Sample Code: let sharedURL = URL(string: "...")! let activityVC = UIActivityViewController(activityItems: [sharedURL], applicationActivities: nil) present(activityVC, animated: true) Sample Image:
1
0
306
Dec ’23
Changing font in CollectionView UIIndexBarAccessoryView
I have a 600 item Collection view for which I implemented a quick access section Index. The implementation uses the usual: indexTitles(for collectionView) and CollectionView(indexPathForIndexTitle: title: at:) All is well, except that the collection titles are in a foreign language (latinized Coptic) and 3 of the 25 title glyphs are not in the SystemFont, so the index is drawn with these titles as question marks in boxes. The problem glyphs are "Ꜣ"(unicode A722), "꟣"(A7E3), and "Ꜥ"(A725) I drilled down on the subviews of the CollectionView and found I could access the index using: let subviews = myCollectionView.subviews if let indexView = subviews.first(where: {String(describing: type(of: $0))=="UIIndexBarAccessoryView"}) { print(indexView) } Examining the contents of this UIIndexBarAccessoryView (which seems to be Private), it contains a _visualStyle property object which holds a _font. How can I "legally" change the font for the indexBarAccessory to one that has the required glyphs? The rest of the App requires the local language to be English(US)
0
0
326
Dec ’23
black screen after switching to UIKit app lifecycle
I had to switch from the SwiftUI app lifecycle to the UIKit lifecycle due to this issue: https://developer.apple.com/forums/thread/742580 When I switch to UIKit I get a black screen on startup. It's the inverse of this issue: https://openradar.appspot.com/FB9692750 For development, I can work around this by deleting and reinstalling the app, but I can't ship an app that results in a black screen for users when they update. Anyone know of a work-around? I've filed FB13462315
3
1
934
Dec ’23
SwiftUI TabBar Icons Disappearing
I have a UIKit tabbar view that contains three views, one of which is a UIViewControllerRepresentable wrapper around a UIKit view controller. Everything works fine except when that wrapped view is visible, the tab bar icons for the other two views disappear. Tapping within their bounds still works to select those views as expected, and they’re even visible in screenshots and in the debug view of the view hierarchy (they also display normally when running the iPad version of the app on Mac), so I’m not sure where to turn except perhaps a bug report. Is this a known issue when running UIKit views within a SwiftUI TabBar or where should I look next?
2
0
731
Dec ’23
Custom keyboard randomly crash with NSExtension Error
I'm currently developing a custom keyboard which bundled with main app. The keyboard would randomly crash when switch between apps with opened custom keyboard on physical device. I've read posts around but seems not what I've encountered. Bundle ID of main app: com.company.appName Bundle ID of keyboard extension: com.company.appName.Keyboard When custom keyboard is opened second time on other app, a sole personality warning would show up, but this won't lead to crash. WARNING! Sole personality is ambiguous; this may lead to erratic behavior [lifecycle] [u 9A2D7B1D-20AF-4E2A-A72F-C37C8D4FDEEA] [com.company.appName.Keyboard(1.0.0)] WARNING! Sole personality is ambiguous; this may lead to erratic behavior; personalities: { "com.companyName.appName.keyboard" = { 19209 = "<PKServicePersonality: 0x28299da00; core = <[u 9A2D7B1D-20AF-4E2A-A72F-C37C8D4FDEEA] [com.company.appName.Keyboard(1.0.0)],[d (null)] [/private/var/containers/Bundle/Application/67892ACC-5BDA-4205-828D-4D94D6E87ABD/AppName.app/PlugIns/Keyboard.appex]>, host pid = 19209>"; 19293 = "<PKServicePersonality: 0x28298fb00; core = <[u DA59190E-D8A2-4109-8D7B-1702E03AB0BD] [com.company.appName.Keyboard(1.0.0)],[d (null)] [/private/var/containers/Bundle/Application/67892ACC-5BDA-4205-828D-4D94D6E87ABD/AppName.app/PlugIns/Keyboard.appex]>, host pid = 19293>"; 299 = "<PKServicePersonality: 0x282981700; core = <[u 61DC0533-3D02-4CE7-83C2-D698537BC6ED] [com.company.appName.Keyboard(1.0.0)],[d (null)] [/private/var/containers/Bundle/Application/67892ACC-5BDA-4205-828D-4D94D6E87ABD/AppName.app/PlugIns/Keyboard.appex]>, host pid = 299>"; }; } After switching between apps for few times, the custom keyboard would crash, common crash log is : Connection to plugin invalidated while in use. 2023-12-13 10:19:44.220973+0800 MobileNotes[36435:1892265] [lifecycle] [u 9A37D3B6-CAE5-4E5C-95FF-DA653DC080E5:m (null)] [com.companyName.appName.Keyboard(1.0.0)] Connection to plugin interrupted while in use. 2023-12-13 10:19:44.221229+0800 MobileNotes[36435:1892265] [lifecycle] [u 9A37D3B6-CAE5-4E5C-95FF-DA653DC080E5:m (null)] [com.companyName.appName.Keyboard(1.0.0)] Connection to plugin invalidated while in use. Another crash log is bit more detailed, but still not sure what it may refers to. ` 2023-12-13 10:19:44.222563+0800 MobileNotes[36435:1892256] [NSExtension] Unable to setup extension context - error: Couldn’t communicate with a helper application. 2023-12-13 10:19:44.222646+0800 MobileNotes[36435:1892256] [NSExtension] Async Begin using internal completion handler called multiple times. Due to error after initial completion: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.company.appName.Keyboard.apple-extension-service" UserInfo={NSDebugDescription=connection to service named com.company.appName.Keyboard-extension-service} Program ended with exit code: 9`
1
0
654
Dec ’23
The format of UITextField is changed after clearing the text and inputting new text.
I have a UITextField and set its text format(font/color/underline) by UITextField.attributedText. However, when I clear the text than input text again, the format is changed. It seems the behavior of attributedText is reset by system after clearing the text. Is this a bug or can we have some workaround to keep the consistent format after clearing the text? The code snippet is like below: let textField = UITextField(frame: CGRectMake(0, 0, 200, 60)) let fontColor = .red let attrText = NSMutableAttributedString(string: "normal text") let range = NSRange(location: 0, length: attrText.length) attrText.addAttribute(.font, value: UIFont.systemFont(ofSize: 14), range: range) attrText.addAttribute(.foregroundColor, value: fontColor, range: range) attrText.addAttribute(.underlineColor, value: fontColor, range: range) attrText.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range) textField.attributedText = attrText
1
0
314
Dec ’23
@available annotation forgotten in showsExpansionTextWhenTruncated
Our app has iOS deployment target as 13. We have used showsExpansionTextWhenTruncated property and is available to iOS 15+. Unfortunately we have used showsExpansionTextWhenTruncated property without if #available(iOS 15, *) and never was failed the build. However, there were many crashes because of that. Should UIKit implement @avaiable in showsExpansionTextWhenTruncated property?
1
0
280
Dec ’23
Are storyboard and UIKit due to disappear ?
I read in Xcode 15.2 release notes that @IBDesignable and @Inspectable are deprecated and will disappear in a future release. After the abandon of WatchKit and its storyboard, replaced by SwiftUI, does it mean storyboards (and consequently UIKit) will progressively disappear, leaving developers alone with SwiftUI to design apps (IMHO, inadequate to design complex UI: for instance, I always struggle to position precisely objects for all devices sizes as we miss constraints manager in SwiftUI) ? For sure, IBDesignable is (was) whimsical, but a very useful tool to design sophisticated UI. Replacing by #Preview does not make it. I also understand that Xcode is a very complex piece of code and that maintaining and evolving some tools (as IBDesignable) requires effort. But isn't it what we expect from Apple ? To provide us with the best tools and keep on the promise of WYSIWYG environments, all along ? Is it only me or do others share this view ?
2
0
1.9k
Dec ’23
UICollectionview Cell textview bounces up - when Keyboard is up and language is selected other than English.
Environment: iOS 15.7.5 Device: iPhone 7 Problem: When collectionview cell textview is in edit mode and keyboard is shown - it bounces up the textview position causing overlaps. Video attached. The issue only occurs on iOS 15 version. It works well in iOS 16, 17 version. The issue occurs when Selected keyboard language is other than English. In ViewController i am updating collectionViewBottomConstraint when keyboard is up or down to enable scroll to the end of collectionview when keyboard is shown. disposable += NotificationCenter.default.reactive .notifications(forName: UIResponder.keyboardWillShowNotification) .take(duringLifetimeOf: self) .observeValues { [weak self] notification in guard let self else { return } let keyboardInfo = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] guard var height = (keyboardInfo as? NSValue)?.cgRectValue.height else { OALogInfo("[SetLocationInfo][VC] height is nil") return } height -= self.view.safeAreaInsets.bottom self.collectionViewBottomConstraint.constant = -height self.collectionViewBottomConstraint.isActive = true } disposable += NotificationCenter.default.reactive .notifications(forName: UIResponder.keyboardWillHideNotification) .take(duringLifetimeOf: self) .observeValues { [weak self] notification in guard let self else { return } self.collectionViewBottomConstraint.constant = 0 self.collectionViewBottomConstraint.isActive = true }
0
0
337
Dec ’23
PKCanvasView: zoom+rotate gesture=ded performance
I'm trying to add rotation functionality to the PKCanvasView, so that rotation gesture rotates the drawing, I want it to be working together with zoom gesture too, which is already implemented in the PKCanvasView. Rotation works reasonably fine when rotation and zoom can't be performed simultaneously. The moment I enable simultaneous zoom+rotation performance of rotation gets noticably bad. Visually it looks like rotation only happens on noticable angles like 10,20,30.. degrees which looks choppy. Zoom at the same time looks smooth as before. I'm trying to understand why and how to fix this. The rotation gesture handler is here: @objc func handleRotation(_ gesture: UIRotationGestureRecognizer) { guard let curView = gesture.view as? PKCanvasView else {return} if gesture.state == .began || gesture.state == .changed { let rotation = gesture.rotation let gestureCenter = gesture.location(in: curView) let center = CGPoint(x: gestureCenter.x / curView.zoomScale, y: gestureCenter.y / curView.zoomScale) let finalTransform = CGAffineTransform(translationX: -center.x, y: -center.y) .concatenating(CGAffineTransform(rotationAngle: rotation)) .concatenating(CGAffineTransform(translationX: center.x, y: center.y)) curView.drawing.transform(using: finalTransform) gesture.rotation = 0 } } which just constructs rotation matrix around rotation gesture center and calls curView.drawing.transform(using: finalTransform). Rotation matrix is correct I think because without simultaneous zoom+rotation it rotates everything as intended and smoothly under any zoom. (Just for clarity: in the rotation handler the matrix does only the rotation, zoom is done in pinch gesture handler implemented by the PKCanvasView. The zoomScale is used in estimations only to figure out the content coodrinate). The handleRotation method is set as let rotationGestureRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(handleRotation)) rotationGestureRecognizer.delegate = self canvasView.addGestureRecognizer(rotationGestureRecognizer) The simultaneous handling of zoom+rotation I enable with this code: func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } What I've tried: Tried to nable simultaneous recognition only for zoom+rotation (without the pan gesture and possible others), the effect is the same. For example rotation+pan work smoothly together. I've verified that the gesture handler is called very often, every 8-16 milliseconds (rotation matrix creation and curView.drawing.transform(using: finalTransform) is included in this time period) which should be enough for visually smooth rotation. Other observations: When zoom and rotation both are enabled the rotation sometimes gets completely stuck, zoom and pinch is responsive but rotation is not happening visually. Only when I release fingers from the screen the rotation unstucks and content is rotated as if it didn't stuck at all. During the "stuck" period the rotation handler is called with the same frequency it's just not being visually reflected. Other thoughts: It kind of looks like the tranformation I set in the rotation handler gets overwritten by transformation from the zoom handler. But pan+rotation works fine together which confuses this theory.
1
0
673
Dec ’23
How to update UIConfigurationState from CollectionView using UIConfigurationStateCustomKey
is there anybody using UIConfigurationStateCustomKey to manage custom state for cells? I want to know if that would be possible to update from the collection view, it’s like UICollectionView.select(indexPath) seems like there is no way for this though. currently UICollectionView (UITableView) can manage is-selected for cells. but provided official property are only available. if we need something another custom properties that describes the cell’s state, we might need make state manager for cells. I was wondering how UIConfigurationStateCustomKey works for us for such case. According to the documentation, we can update the custom state from only visible cell. so we can not update currently hidden cell’s state. https://developer.apple.com/documentation/uikit/uiconfigurationstatecustomkey
0
0
324
Dec ’23
UIHostingController wrong height animation
In iOS 17, whenever I change the height of a UIHostingController in a animation block, the root SwiftUI.View ignores it: class TestAnimationController: UIViewController { var heightConstraint: NSLayoutConstraint! // a basic trigger override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) heightConstraint.constant = heightConstraint.constant == 300 ? 100 : 300 UIView.animate(withDuration: 1.0) { self.view.layoutIfNeeded() } } override func viewDidLoad() { super.viewDidLoad() let content = UIHostingController(rootView: Color.red) addChild(content) view.addSubview(content.view) content.view.translatesAutoresizingMaskIntoConstraints = false heightConstraint = contentView.heightAnchor.constraint(equalToConstant: 100) heightConstraint.isActive = true contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true content.didMove(toParent: self) } } The result is terrible: It was not the case in iOS 14.5: Does someone have a workaround?
2
0
642
Dec ’23
UIAlertAction has a poor color contrast ratio in destructive style
Hi Folks, I am reaching out for an iOS A11y color contrast issue, which I have also fired a bug report 12525894 but does not get any reply. The UIAlertAction in destructive style has a poor color contrast ratio of less than 4.5: 1 between text color and background color. This applies to any system/third party app which uses UIAlertViewController from UIKit and Alert from SwiftUI (Take the system Photos app as an example). Given that the "titleTextColor" property from UIAlertAction class is private, developers have no ways to modify the alert action to make it WCAG compatible. Here is an example of the Photo app alert. The text "Delete Photo" (#EB4E3D) should have a contrast ratio of at least 4.5 to 1 against its background(#EAEBE7) to comply to the Web Content Accessibility Guidelines (WCAG). Actual result: The text "Delete Photo" (#EB4E3D) has a contrast ratio of 3.08 to 1 against its background(#EAEBE7), which does not match 4.5:1 Web Content Accessibility Guidelines (WCAG).
0
0
555
Dec ’23
Setting a tint color for a SF Symbol or System Item using Navigation Controller's UIAppearance API
Hi, I'm working on a View Controller where the Navigation Controller's UIBarButtonItems, composed of SF Symbol images and/or System Items, should change their tint color based on the current Navigation Controller scroll edge or default appearance. let buttonAppearance: UIBarButtonItemAppearance = .init(style: .plain) buttonAppearance.normal.titleTextAttributes = [.foregroundColor: color] standardAppearance.buttonAppearance = buttonAppearance I've used UIBarButtonItemAppearance titleTextAttributes to successfully change a UIButton's label text color, but I wasn't able to find a supported method under the UIAppearance API to do the same update to images. I'd highly appreciate clarification on whether or not it is supported and, if not, what could be some alternatives. Specs: iOS 16+ Thanks!
1
0
590
Dec ’23
App crashed on reading image in bundle when there is only a color with the same name.
Related APIs: +[UIImage imageNamed:] +[UIImage imageNamed:inBundle:compatibleWithTraitCollection:] When there is only a color set with the name (no image set provided), reading the image with the above-mentioned APIs throws an exception: 2023-12-19 19:30:34.008701+0800 ***[57410:578064] *** Assertion failure in -[_UIImageCGImageContent initWithCGImageSource:CGImage:scale:], _UIImageContent.m:666 2023-12-19 19:30:34.031207+0800 ***[57410:578064] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Need an imageRef' Even when wrapped in a try/catch block, it still crashes due to a lock issue after calling the related API twice. Here is an example code snippet: UIImage *image; for (NSInteger i=0; i<10; i++) { @try { image = [UIImage imageNamed:@"sample"]; //image = [UIImage imageNamed:@"sample" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil]; } @catch (NSException *exception) { } } The crash backtrace is as follows: #0 0x0000000102b12214 in _os_unfair_lock_recursive_abort () #1 0x0000000102b0da50 in _os_unfair_lock_lock_slow () #2 0x000000010ab07624 in -[UIImageAsset imageWithConfiguration:] () #3 0x000000010b2f4634 in -[_UIAssetManager imageNamed:configuration:] () #4 0x000000010aaf2394 in +[UIImage imageNamed:inBundle:withConfiguration:] () #5 0x000000010aaf2200 in +[UIImage imageNamed:inBundle:compatibleWithTraitCollection:] () #6 0x0000000105442154 in +[UIImageAccessibility imageNamed:inBundle:compatibleWithTraitCollection:] () It seems that the color set is being treated as an imageRef in this image reading process. It's a bug of UIKit?
1
0
860
Dec ’23
UIViewController asynchronous deallocation issues
i’ve seen evidence that UIViewController has logic to prevent its dealloc/deinit methods from running on a background thread. what seems to occur is that, if the last strong reference to a UIVC is zeroed off the main thread, then the VC is logically marked as ‘deallocating’, but actual invocation of dealloc/deinit is enqueued to the main queue. during the window of time between the beginning and end of this asynchronous deallocation, some strange issues can occur. in particular, if the deallocating VC is a parent view controller, then its children can still access it via their parent property. despite this property being marked as weak, a non-nil parent VC reference will be returned. if a weak reference is attempted to be stored to the parent, you get a runtime crash immediately to the effect of: Cannot form weak reference to instance (0x1234) of class <some-UIVC-sublass>... surprisingly, if you load the reference via the objc runtime's objc_loadWeak method, you'll get nil, but no crash. unsurprisingly, if a strong reference to the deallocating parent is stored and persists past its dealloc invocation, you’ll generally end up with a segmentation violation if the reference is accessed. i imagine the UIVC source is quite complex and there are probably good reasons to try and ensure deallocation only ever occurs on the main thread, but it seems surprising that simply passing view controller variables across threads could lead to exposing unsafe references like this. is this behavior expected? assuming not, i've preemptively filed feedback FB13478946 regarding this issue. attached is some sample code that can reliably reproduce the unexpected behavior. UIKitAsyncDeallocCrashTests.swift
1
0
767
Dec ’23
Custom view animates from bottom - up at first, but not afterwards.
I have this ToastView that will animate by expanding the height from the top of the screen. All the components are created programmatically. This is the code: final class ToastView: UIView { private static let instance = createContainer() private let labelHeightOffset: CGFloat = 32 private let messageLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.numberOfLines = 0 return label }() private var heightConstraint: NSLayoutConstraint! static func show(message: String) { let keyWindow = UIWindow.getKeyWindow() //extension to get the kley window show(on: keyWindow, message: message) } private static func show(on parentView: UIView? = nil, message: String) { guard let parentView = parentView ?? UIViewController.getTopViewController()?.view, instance.superview == nil, let toast = toast else { return } parentView.addSubview(instance, method: .fill) toast.messageLabel.text = message toast.messageLabel.textColor = .red toast.messageLabel.textAlignment = .center toast.messageLabel.sizeToFit() toast.show(for: 3) } private func show(for duration: TimeInterval = 0) { isHidden = false layoutIfNeeded() UIView.animate(withDuration: 0.4, animations: { let labelLineHeight = self.messageLabel.getRect(maxLine: 3).size.height //getRect is an extension func to get the rect based on the content of the label let lineSpaces = CGFloat((self.messageLabel.getLineNumber() - 1) * 2) //getLineNumber is an extension func to get the total number of lines based on the content //Get the height by the content of the label self.heightConstraint.constant = self.labelLineHeight + self.labelHeightOffset + lineSpaces self.setNeedsUpdateConstraints() self.superview?.layoutIfNeeded() }, completion: { _ in self.hide(delay: duration) }) } private func hide(delay: TimeInterval = 0) { UIView.animate(withDuration: 0.4, delay: delay, animations: { self.heightConstraint.constant = 0 self.setNeedsUpdateConstraints() self.superview?.layoutIfNeeded() }, completion: { _ in self.isHidden = true self.messageLabel.text = nil ToastView.instance.removeFromSuperview() }) } } private extension ToastView { static var toast: ToastView? { return instance.subviews[0] as? ToastView } static func createContainer() -> UIView { let container = UIView(frame: .zero) container.backgroundColor = .clear let toast = ToastView(frame: .zero) toast.backgroundColor = .white toast.addCorner(radius: 8) container.addSubview(toast) toast.layoutMessageLabel() toast.layoutToast() return container } func layoutMessageLabel() { addSubview(messageLabel) messageLabel.center = center messageLabel.translatesAutoresizingMaskIntoConstraints = false let constraints = [ centerYAnchor.constraint(equalTo: messageLabel.centerYAnchor), leftAnchor.constraint(equalTo: messageLabel.leftAnchor, constant: 16), rightAnchor.constraint(equalTo: messageLabel.rightAnchor, constant: 16) ] NSLayoutConstraint.activate(constraints) messageLabel.setNeedsUpdateConstraints() layoutIfNeeded() } func layoutToast() { translatesAutoresizingMaskIntoConstraints = false let topConstants: CGFloat = UIWindow.getKeyWindow()?.safeAreaInsets.top ?? 0 + 16 let topConstraint = topAnchor.constraint(equalTo: superview!.topAnchor, constant: topConstants) heightConstraint = heightAnchor.constraint(equalToConstant: 0) let constraints = [ topConstraint, heightConstraint!, leftAnchor.constraint(equalTo: superview!.leftAnchor, constant: 16), superview!.rightAnchor.constraint(equalTo: rightAnchor, constant: 16) ] NSLayoutConstraint.activate(constraints) setNeedsUpdateConstraints() superview!.layoutIfNeeded() } } The code is working fine EXCEPT for the first time it appears. It always animates from the bottom of the screen and rising above ot the top. But if you'll have a look at the code, I only animte the heightConstraint's constant value. Why is this happening? Can you help me fix this? thanks.
1
0
966
Dec ’23
A bug for Accessibility
on iOS, when VoiceOver is running, double click the UITextView can quickly switch the cursor between the beginning and end of the text. Problem the problem is, when the text contains some NSTextAttachment, this ability has failed. Here is some code to reproduce this problem. import UIKit class ViewController: UIViewController { private var textView: UITextView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.backgroundColor = UIColor.white textView = UITextView(frame: CGRect(x: 60, y: 220, width: 240, height: 180)) textView?.layer.borderColor = UIColor.black.cgColor textView?.layer.borderWidth = 1 textView?.font = .systemFont(ofSize: 18) view.addSubview(textView!) let button = UIButton(type: .system) button.frame = CGRect(x: 120, y: 120, width: 60, height: 60) button.setTitle("click", for: .normal) button.addTarget(self, action: #selector(self.click), for: .touchUpInside) view.addSubview(button) } @objc func click() { let emojiImage = UIImage(systemName: "iphone.circle") let lineHeight = UIFont.systemFont(ofSize: textView!.font?.pointSize ?? 0.0).lineHeight let insertedAttr = generateAttributedString(image: emojiImage, bounds: CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)) let attr = NSMutableAttributedString(attributedString: textView!.attributedText) attr.replaceCharacters(in: textView!.selectedRange, with: insertedAttr) textView!.attributedText = attr } public func generateAttributedString(image: UIImage?, bounds: CGRect) -> NSMutableAttributedString { let attachment = NSTextAttachment(data: nil, ofType: nil) attachment.bounds = bounds attachment.image = image let attrString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment)) attrString.addAttribute(.font, value: textView!.font!, range: NSRange(location: 0, length: attrString.length)) return attrString } }
1
0
405
Dec ’23