There are two ways to capture application transitioning to foregorund/background and inactive/active. Lets take the event received when app transitions to the inactive state as an example.
Implement the corresponding AppDelegate method - applicationWillResignActive(_:)
func applicationWillResignActive(_ application: UIApplication) {
Log("applciationWillResignActive(_:)")
}
Register for willResignActiveNotification during startup
NotificationCenter.default.addObserver(forName:UIApplication.willResignActiveNotification, object: nil, queue: .main) { (broadcastNotification: Notification) in
Log("Received " + String(describing: broadcastNotification.name))
}
When I tested in code, both works. First, the applicationWillResignActive(_:) delegate method is invoked and then, willResignActiveNotification is received (as mentioned in the documentation).
But I'm unable to decide which to use... even after reading their documentation. What is the recommendation? If both are fine, then there are two different ways to achieve the same thing... there's gotta be some purpose, right?
UIKit
RSS for tagConstruct and manage graphical, event-driven user interfaces for iOS or tvOS apps using UIKit.
Post
Replies
Boosts
Views
Activity
Our product is an iOS native App. When we adapted our app to iOS 17, the text displayed by the UILabel was out of tune.
Here are the details:
Device: iPhone 14 Pro
Version: iOS 17 Beta1 〜 Beta7
UILabel: height is dynamic
Inconsistency:
Before iOS 17, UILabel displayed text "銀行口座との連携を解除します。よろしいですか" by two lines.
However, on iOS 17, it shows "銀行口座との連携を解除します。..." instead.
question:
Which API changes may cause this inconsistent text display
Is it meant to be fixed. If so, how to fix it?
Bonjour je travaille sur main storyboard mais quand je mets un bouton pour aller de mon View controller à un autre View controller. J'appuie sur control, je clique show et je ***** sur le simulateur iOS 17 ( iPhone 14 pro max ) et quand je clique sur mon bouton ça me fait un segue Present Modally.
Comment puis je faire pour avoir un vraie segue show à la place d'un segue Present Modally.
Merci
I love the new UIImage(resource:) initializer that uses the automatically generated symbols for my image assets.
However, there does not appear to be an equivalent in SpriteKit so I am forced to still use SKSpriteNode(imageNamed:)
I am using Xcode 15 Beta 7.
Will this be included when Xcode 15 goes into production?
I trying to display toast on bottom of screen but, when keypad appears toast is hiding behind keypad. Please any one suggest me the solution. Below is my code which i tried.
func displayToast(_ message : String) {
guard let delegate = UIApplication.shared.delegate as? AppDelegate, let window = delegate.window else {
return
}
if let toast = window.subviews.first(where: { $0 is UILabel && $0.tag == -1001 }) {
toast.removeFromSuperview()
}
let toastView = UILabel()
toastView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
toastView.textColor = UIColor.white
toastView.textAlignment = .center
toastView.font = UIFont(name: "Font-name", size: 17)
toastView.layer.cornerRadius = 15
toastView.clipsToBounds = true
toastView.text = message
toastView.numberOfLines = 0
toastView.alpha = 0
toastView.translatesAutoresizingMaskIntoConstraints = false
toastView.tag = -1001
let windowww = UIApplication.shared.windows[UIApplication.shared.windows.count - 1]
windowww.addSubview(toastView)
let horizontalCenterContraint: NSLayoutConstraint = NSLayoutConstraint(item: toastView, attribute: .centerX, relatedBy: .equal, toItem: windowww, attribute: .centerX, multiplier: 1, constant: 0)
let widthContraint: NSLayoutConstraint = NSLayoutConstraint(item: toastView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: (self.frame.size.width-25) )
let verticalContraint: [NSLayoutConstraint] = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=200)-[toastView(==50)]-68-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["toastView": toastView])
NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint])
NSLayoutConstraint.activate(verticalContraint)
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
toastView.alpha = 1
}, completion: nil)
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3), execute: {
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
toastView.alpha = 0
}, completion: { finished in
toastView.removeFromSuperview()
})
})
}
I'm trying to add sodas from ListView to ContentView and have that data passed on and update the view in AisleView. I'm having a lot of trouble getting my columnOne and columnTwo properties to update the AisleView correctly. I know the data is being passed to AisleView, but it isn't updating the actual view. I believe the issue is when I'm trying to initialize my columns. Any help would be appreciated. Thank you!
class Inventory {
var inventory: [Product] = [
Product(name: "Coke", price: 2.99, aisle: 1, location: 10),
Product(name: "Pepsi", price: 3.99, aisle: 1, location: 6),
Product(name: "Dr. Pepper", price: 1.99, aisle: 2, location: 8),
Product(name: "Pibb", price: 1.50, aisle: 2, location: 1)
]
}
struct ListView: View {
@State var base = Inventory()
@State var sodas: [Product] = []
var body: some View {
VStack {
ContentView(sodas: $sodas)
List {
ForEach(base.inventory) { product in
HStack {
Text(product.name)
Spacer()
Text("\(product.price, specifier: "%.2f")")
Button {
sodas.append(product)
} label: {
Image(systemName: "plus")
}
}
}
}
}
}
}
struct ListView_Previews: PreviewProvider {
static var previews: some View {
ListView()
}
}
struct ContentView: View {
@Binding var sodas: [Product]
@State private var columnOne: [Product] = []
@State private var columnTwo: [Product] = []
init(sodas: Binding<[Product]>) {
self._sodas = sodas
self.columnOne = aisleSort(sodas: self.sodas, aisle: 1)
self.columnTwo = aisleSort(sodas: self.sodas, aisle: 2)
}
var body: some View {
VStack {
HStack(spacing: 10) {
AisleView(products: $columnOne)
AisleView(products: $columnTwo)
}
}
}
func aisleSort(sodas: [Product], aisle: Int) -> [Product] {
var sort: [Product] = []
for soda in sodas {
if soda.aisle == aisle {
sort.append(soda)
}
}
return sort
}
}
struct AisleView: View {
@Binding var products: [Product]
@State private var buttonNumber = 0
var location: [Int] {
var answer: [Int] = []
for number in products {
answer.append(number.location)
}
return answer
}
func idicator(number: Int) -> Color {
if location.contains(number) {
return Color.red
} else {
return Color.primary
}
}
var body: some View {
ZStack {
VStack(alignment: .center, spacing: 0) {
ForEach(1..<21, id: \.self) {number in
ZStack {
if location.contains(number) {
Button {
buttonNumber = number
} label: {
HStack {
Rectangle()
.foregroundColor(.red)
.frame(width: 20, height: 20)
}
}
.overlay(buttonNumber == number ? InfoView(sodas: products, number: number).offset(x: -70) : nil)
} else {
HStack {
Rectangle()
.frame(width: 20, height: 20)
.foregroundColor(idicator(number: number))
Text("\(number)")
}
}
}
}
}
}
}
}
struct InfoView: View {
@State var sodas: [Product]
@State var number: Int
var body: some View {
VStack {
ForEach(sodas) { soda in
if soda.location == number {
ZStack {
RoundedRectangle(cornerRadius: 10)
.foregroundColor(.clear)
.background(.regularMaterial)
.clipShape(RoundedRectangle(cornerRadius: 10))
VStack {
Text(soda.name)
Text("$\(soda.price, specifier: "%.2f")")
}
// .font(.title)
}
.frame(width: 100, height:60)
}
}
}
}
}
struct AisleView_Previews: PreviewProvider {
static var previews: some View {
AisleView(products: ListView().$sodas)
}
}
`
The cell in question has a disclosure option set as:
let disclosureOptions = UICellAccessory.OutlineDisclosureOptions(style: .header)
let accessory: UICellAccessory = .outlineDisclosure(options: disclosureOptions)
cell.accessories = [accessory]
My requirement is to keep only one item in the whole section expandable.
I observe for the collapse and expansion changes below:
dataSource.sectionSnapshotHandlers.willCollapseItem = { [weak self] item in
guard let self = self else { return }
if item == self.expandedArticleItem {
self.expandedArticleItem = nil
}
}
dataSource.sectionSnapshotHandlers.willExpandItem = { [weak self] item in
guard let self = self else { return }
if self.expandedArticleItem == nil {
self.expandedArticleItem = item
} else {
guard let sectionForItem = self.dataSource
.snapshot()
.sectionIdentifier(containingItem: item),
let expandedItem = self.expandedArticleItem
else { return }
var sectionSnapshot = self.dataSource.snapshot(for: sectionForItem)
sectionSnapshot.collapse([expandedItem])
self.dataSource.apply(sectionSnapshot, to: sectionForItem,
animatingDifferences: false)
self.expandedArticleItem = item
}
}
This code does the job of keeping only item expanded but the default disclosure indicator still points down "v" for cells that is not visible currently but was earlier expanded and is now collapsed.
I used the Local Folder UIKit-Based ViewController Module to select three Xcode projects that may work differently with string values stored in each Xcode Project Helper File.
However, I have Successfully converted that Module to an Independent Swift Package And was able to deploy it on GitHub for easy use with different projects without having to update each file everywhere.
But Now the string value that the Package depended on is not taking that value from the Xcode project it has been added to.
So, How do we get value from the Xcode project for an independently added Swift Package to make it work?
On devices running iOS 17 public beta 6 and our application, there are reports of crash related to NSInternalInconsistencyException, UIMenu._resolvedElementSize cannot be called before the menu has been prepared for display.
Our application uses the WKWebView which loads HTML pages and run JavaScript. The crash seems to happen randomly but usually as a result of interacting with UI elements.
This crash was not seen on iOS 16.6, which is currently the latest public version.
See the following stack trace that was captured by our application :
#1 0x1b309bc00 : objc_exception_throw
#2 0x1ba29d808 :
#3 0x1bd489188 -[UIMenu::_resolvedElementSize]
#4 0x1bd48eebc :
#5 0x1bd48f1dc :
#6 0x1bdbc4468 -[_UIContextMenuListView::setDisplayedMenu:]
#7 0x1bd3111f4 -[_UIContextMenuView::_newListViewWithMenu:position:]
#8 0x1bd310108 -[_UIContextMenuView::_displayMenu:inPlaceOfMenu:updateType:alongsideAnimations:]
#9 0x1bde9e038 -[_UIContextMenuUIController::presentationTransitionWillBegin]
#10 0x1bddc6718 -[_UIContextMenuPresentation::prepareToPresent]
#11 0x1bcea0f58 +[UIView::performWithoutAnimation:]
#12 0x1bd339f4c -[_UIRapidClickPresentationAssistant::_performPresentationAnimationsFromViewController:]
#13 0x1bd339d8c -[_UIRapidClickPresentationAssistant::presentFromSourcePreview:lifecycleCompletion:]
#14 0x1bdc06b10 :
#15 0x1bd121544 :
#16 0x1bdc06ac0 :
#17 0x1bdc068e8 -[_UIClickPresentationInteraction::_performPresentation]
#18 0x1bdc083f4 :
#19 0x1bd031e44 :
#20 0x1bdc0606c -[_UIClickPresentationInteraction::_performPreviewPresentation]
#21 0x1be105734 :
#22 0x1be108a54 :
#23 0x1be10894c -[UIContextMenuInteraction::_interactionShouldBeginAtPlatformPoint:completion:]
#24 0x1be1056f4 -[UIContextMenuInteraction::_presentMenuAtPlatformPoint:]
I keep getting random crashes, when attempting to reconfigure an existing item. I check immediately for that if the item identifier exists in the data source and do not attempt to configure it if it's not. This is there error message: "Attempted to reconfigure item identifier that does not exist in the snapshot: ..."
Fatal Exception: NSInternalInconsistencyException
0 CoreFoundation 0x9cb4 __exceptionPreprocess
1 libobjc.A.dylib 0x183d0 objc_exception_throw
2 Foundation 0x4e154c _userInfoForFileAndLine
3 UIKitCore 0xa44a8 -[__UIDiffableDataSourceSnapshot _validateReloadUpdateThrowingIfNeeded:]
4 UIKitCore 0xa2ed8 -[__UIDiffableDataSourceSnapshot _commitUpdateAtomic:]
5 UIKitCore 0x561048 -[__UIDiffableDataSourceSnapshot reconfigureItemsWithIdentifiers:]
6 libswiftUIKit.dylib 0x35d0c NSDiffableDataSourceSnapshot.deleteItems(_:)
7 Trulia 0x45380c closure #1 in ActivityFeedV3ViewController.updateUI(for:)
8 Trulia 0x4c4f58 thunk for @escaping @callee_guaranteed () -> () (<compiler-generated>)
Calling loadFileRepresentationForTypeIdentifier sometimes returns an empty file, the URL params is filled with a path where a file exists, however it contains empty content.
My app is released on the store and this error happens 1.5% of the time my users pick an image / video from their gallery using the UIImagePickerControllerDelegate.
I was able to reproduce this bug and here is a screenshot of XCode in debug mode so you can see that the file is empty right after calling loadFileRepresentationForTypeIdentifier
I'm using XCode 14.3.1, a real iPhone 12 with iOS 16.3.1 and coding in Objective-C.
Step to repro :
1- Capture a live photo with your device
2- Pick this photo from your gallery using UIImagePickerControllerDelegate -> didFinishPicking
3- Grab the item provider and call provider loadFileRepresentationForTypeIdentifier:@"public.jpeg"
4- Inside the completion handler check the file size of the URL provided in the parameters
It is 1.5% repro, so to repro in local I had to take hundreds of live photos. But with patience, it happens and you can debug.
Note: Calling a second time loadFileRepresentationForTypeIdentifier:@"public.jpeg" inside the completionHandler returns a URL pointing to a real file with existing content, thus there might be some race conditions somewhere.
Do you have any workarounds?
Hello there!
UIDocumentInteractionController.name property doesn't seem to work as documented. Here's the sample code:
class ViewController: UIViewController {
// ...
func showShareController(with sourceView: UIView) {
// ...
let attachment = MyAttachment(name: "MyDoc.pdf", url: URL(string: "path/to/<MyDocInternalUUIDName>.pdf")!, uti: UTType(mimeType: "application/pdf"))
let sourceViewRect = view.convert(sourceView.bounds, from: sourceView)
documentInteractionController = UIDocumentInteractionController(url: attachment.url)
documentInteractionController?.uti = attachment.uti?.identifier
documentInteractionController?.name = attachment.name
documentInteractionController?.delegate = self
documentInteractionController?.presentOptionsMenu(
from: sourceViewRect,
in: view,
animated: true
)
}
}
The share sheet is presented successfully, as well the file is available to share via some service (I've used AirDrop from the test device to my MacBook). However, in the navigation bar I see the internal UUID filename, and it's shared to my MacBook with the very same name:
Is this a bug or am I missing something?
UIColorPickerViewController opens, but does not work and appears incorrect
// swiftui
@State private var showDialog = false
@State private var color: Color = .white
// some code swiftui
Button("Title") {
showDialog = true
}
.sheet(isPresented: $showDialog) {
ColorPickerViewRepresentable(color: $color)
}
// uikit
struct ColorPickerViewRepresentable: UIViewControllerRepresentable {
@Binding var color: Color
func makeUIViewController(context: Context) -> UIColorPickerViewController {
let vc = UIColorPickerViewController()
vc.delegate = context.coordinator
vc.selectedColor = UIColor(color)
vc.supportsAlpha = false
return vc
}
func updateUIViewController(_ uiViewController: UIColorPickerViewController, context: Context) {
uiViewController.selectedColor.resolvedColor(with: UITraitCollection.current)
}
func makeCoordinator() -> Coordinator {
return Coordinator(parent: self)
}
class Coordinator: NSObject, UIColorPickerViewControllerDelegate {
var parent: ColorPickerViewRepresentable
init(parent: ColorPickerViewRepresentable) {
self.parent = parent
}
func colorPickerViewControllerDidFinish(_ viewController: UIColorPickerViewController) {
parent.color = Color(uiColor: viewController.selectedColor)
}
}
}
The default font seems to be .AppleSystemUIFont based on UIFont.preferredFont(forTextStyle: .body).familyName. How can it be selected in a UIFontPickerViewController so that users can revert back to the original default font?
import SwiftUI
class FontPickerViewController: UIViewController, UIFontPickerViewControllerDelegate {
var isPickerPresented: Binding<Bool>?
var onFontPick: ((UIFontDescriptor) -> Void)?
override func loadView() {
super.loadView()
let button = UIButton(type: .system)
button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .body)
button.setTitle("Choose font", for: .normal)
button.addTarget(self, action: #selector(showFontPicker), for: .touchUpInside)
button.sizeToFit()
button.backgroundColor = .clear
view = button
}
func fontPickerViewControllerDidPickFont(_ viewController: UIFontPickerViewController) {
dismiss(animated: true)
isPickerPresented?.wrappedValue = false
guard let fontDescriptor = viewController.selectedFontDescriptor else { return }
onFontPick?(fontDescriptor)
}
func fontPickerViewControllerDidCancel(_ viewController: UIFontPickerViewController) {
dismiss(animated: true)
isPickerPresented?.wrappedValue = false
}
@objc func showFontPicker() {
let configuration = UIFontPickerViewController.Configuration()
configuration.includeFaces = true
configuration.displayUsingSystemFont = false
let fontPicker = UIFontPickerViewController(configuration: configuration)
fontPicker.delegate = self
present(fontPicker, animated: true)
isPickerPresented?.wrappedValue = true
}
}
struct FontPickerViewControllerRepresentable: UIViewControllerRepresentable {
@Binding var isPickerPresented: Bool
var onFontPick: (UIFontDescriptor) -> Void
public func makeCoordinator() -> Coordinator {
return Coordinator(self, onFontPick: self.onFontPick)
}
public class Coordinator {
var parent: FontPickerViewControllerRepresentable
let picker = FontPickerViewController()
init(_ parent: FontPickerViewControllerRepresentable, onFontPick: @escaping (UIFontDescriptor) -> Void) {
self.parent = parent
picker.onFontPick = onFontPick
picker.isPickerPresented = parent._isPickerPresented
}
}
func makeUIViewController(context: Context) -> FontPickerViewController {
context.coordinator.picker
}
func updateUIViewController(_ uiViewController: FontPickerViewController, context: Context) {
if isPickerPresented {
context.coordinator.picker.showFontPicker()
} else {
}
}
@available(iOS 16.0, *)
func sizeThatFits(_ proposal: ProposedViewSize, uiViewController: FontPickerViewController, context: Context) -> CGSize? {
uiViewController.view.intrinsicContentSize
}
}
struct FontPicker: View {
@State var isPickerPresented = false
@State var selectedFont: UIFont?
var font: Font? {
if let selectedFont {
return Font(selectedFont)
}
return nil
}
var body: some View {
Button {
isPickerPresented = true
} label: {
HStack {
FontPickerViewControllerRepresentable(isPickerPresented: $isPickerPresented) { fontDescriptor in
let size = UIFont.preferredFont(forTextStyle: .body).pointSize
let font = UIFont(descriptor: fontDescriptor, size: size)
selectedFont = font
}
Spacer()
Text(selectedFont?.familyName ?? "Not Selected")
.font(font)
.foregroundColor(.secondary)
}
}
.onAppear {
print(UIFont.preferredFont(forTextStyle: .body))
}
}
}
}
struct Test3_Previews: PreviewProvider {
static var previews: some View {
Form {
FontPicker()
let defaultFont = UIFont.preferredFont(forTextStyle: .body)
Text(defaultFont.familyName)
Text(defaultFont.fontName)
}
}
}
Hi, I found an issue while developing with iOS 17 beta again.
This issue only occurs on iOS 17 beta and iPhone 14 Pro Max Dynamic lsland devices.
When we go back from landscape to portrait, the UINavigationBar on the portrait screen is offset by center 215, 273, and by changing the frame and center of the UINavigationBar in the code the next time we go to the page it will still be offset.
The problem only occurs the first time to enter the horizontal screen to return, and then enter the horizontal screen again to return to the problem will disappear.
To go to landscape we use custom transitions
From recent days we are facing a serious random crash issue in our iOS app related to UICollectionView. We are having listing page where we have 4 sections with different data model. We have faced the below crash issue which happened all times when we update collection view.
NSInternalInconsistencyException - Invalid update: invalid number of items in section 3. The number of items contained in an existing section after the update (60) must be equal to the number of items contained in that section before the update (40), plus or minus the number of items inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).
With below solution
if #available(iOS 15.0, *) {
if isPagination {
var paths = [IndexPath]()
for item in 0..<(localResult.products?.items ?? []).count {
let indexPath = IndexPath(row: item + self.productItemData.count, section: 3)
paths.append(indexPath)
}
self.productItemData.append(contentsOf: localResult.products?.items ?? [])
self.mainCollectionView?.insertItems(at: paths)
} else {
self.productItemData.append(contentsOf: localResult.products?.items ?? [])
}
} else {
self.productItemData.append(contentsOf: localResult.products?.items ?? [])
}
With the above solution, crash which happened all times when we update the collection view is resolved. But now, we are facing with another new issue as below and this is happening randomly based on different data set. This crash log is becoming the highest one and its affecting our app performance very seriously. And its happening with mostly above iOS 15. Is there any gap that we missed with latest iOS version update and why its happening without any much code change? Any better solution will be appreciated.
Latest crash details:
NSInternalInconsistencyException - attempt to insert item 20 into section 3, but there are only 3 sections after the update
NSInternalInconsistencyException - Invalid batch updates detected: the number of sections and/or items returned by the data source before and/or after performing the batch updates are inconsistent with the updates.
Data source before updates = { 4 sections with item counts: [1, 1, 1, 340] }
Data source after updates = { 4 sections with item counts: [1, 1, 1, 340] }
Updates = [
Insert item (3 - 320),
Insert item (3 - 321),
Insert item (3 - 322),
Insert item (3 - 323),
Insert item (3 - 324),
Insert item (3 - 325),
Insert item (3 - 326),
Insert item (3 - 327),
Insert item (3 - 328),
Insert item (3 - 329),
Insert item (3 - 330),
Insert item (3 - 331),
Insert item (3 - 332),
Insert item (3 - 333),
Insert item (3 - 334),
Insert item (3 - 335),
Insert item (3 - 336),
Insert item (3 - 337),
Insert item (3 - 338),
Insert item (3 - 339)
]
I currently have a UIKit app which uses a UIStoryboard and which has a tab bar controller. I removed the tab bar controller from the storyboard and created a tab bar app in SwiftUI which has the UIKit views represented as UIViewControllerRepresentable within structs. I changed the visionOS app destination from 'visionOS Designed for iPad' to 'visionOS' because I want to see the tabs on the left side in visionOS. I got a ton of warnings and some errors. I fixed the errors (which were related to user location). But the warnings are with regards to the storyboard and storyboard segue. The app runs perfectly fine but the warnings warn that UIStoryboard and UIStoryboardSegue will not be supported in a future version of visionOS. I wonder first why this was done and second, how much time will I have to fix the warnings? Could I release the app as is and fix later or will the support be dropped in a short timeframe? One of the ways to create views for view controllers in UIKit is through a storyboard. If you kill those in visionOS, then you restrict a big way that one can embed a UIKit view controller in SwiftUI.
Hello!
I've tested/implemented TipKit in SwiftUI and UIKit but it seems that the close, i.e. X, button doesn't work in UIKit but does in SwiftUI. Not sure if this is a bug or I have to do something different about it in UIKit.
Testing with Xcode 15 Beta 8
Thanks!
For my use case i need to access the same intance of MyViewController ,which i am using in UIViewRepresentable for adding it to SwiftUI herierchy .And to achive that i am creating a static intance of MyViewController and using it in objective c function to make changes in viewcontroller as well as adding it in SwiftUI view hireiachy . Is this a right apprach to use ? I dont find any documentation by apple which suggest this approach .
Just want to validate it here .
And also Is this method of using UIRepresentableController right method to use in my UIkit's view controller in SwiftUI and updating viewcontroller from objectiveC ? or is there any other approach to achieve this ?
Entry Point :
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
SwiftUIView()
}
}
}
SwiftUIView:
import SwiftUI
struct SwiftUIView: View {
var body: some View {
UIKitToSwiftUIBridge ()
}
}
UIKitToSwiftUIBridge:
import SwiftUI
import UIKit
struct UIKitToSwiftUIBridge: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> MyViewController {
let viewcontroller = SharedViewController.sViewController
return viewcontroller
}
func updateUIViewController(_ uiViewController: MyViewController, context: Context) {
}
}
SharedViewController :
{
static let sViewController = MyViewController ()
private override init () {
}
@objc static func GetViewController ()->MyViewController
{
return SharedViewController.sViewController
}
}
MyViewController.swift :
import UIKit
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .black
let button = UIButton (frame : CGRect (x:50, y:100, width:100, height:50))
button.setTitle("Button", for: .normal)
button.addTarget(self, action: #selector(ButtonAction (_:)), for: .touchDown)
}
@objc
func ButtonAction (_ sender :UIButton)
{
let view = UIView (frame: CGRect (x:0, y:0, width:300, height:400))
view.backgroundColor = .red
let label = UILabel (frame: CGRect(x: 60, y: 50, width: 150, height: 60))
label.text = " Label"
view.addSubview(label)
self.view.addSubview(view)
}
@objc
func ChangeColor () {
self.view.backgroundColor = .white
}
}
Objective C code where i need to access MyViewController's intance :
void ObjectiveC::ChangeColorOfViewController ()
{
dispatch_async( dispatch_get_main_queue (),^{
MyViewController * sharedobj = [SharedObject sharedMethod];
[sharedobj ChangeColor];
});
}
I recently was thinking about which is the best format to use for my little icons in the app, and was considering the performance of PNG versus SVG . I know that PNG decoders are hardware accelerated and parallelized, and the rendering is as simple as placing the pixels on the screen.
On the other hand, SVG requires computation to determine the placement of pixels based on mathematical equations.
Considering this, my current assumption is that PNG is faster to render than SVG. However, if SVG is also hardware-accelerated, it could alter the situation, although this may not be the case.