Auto Layout

Create a user interface that dynamically responds to changes in the available screen space using Auto Layout.

Posts under Auto Layout tag

77 results found
Post marked as solved
51 Views

Managing External Subviews and Layout

I'm writing a Mac OS app in Objective-C. The mainWindowController has a vertical NSSplitView in the application's window. This split view is in the mainWindowController's nib file. In mainWindowController's viewDidLoad, I instantiate two child controllers--call them A and B. A and B each have their own nib that contains nothing but an NSView. Later, A and B will instantiate children objects in their own viewDidLoad, giving a hierarchy. As you may expect, A's view and B's view form the left and right panes of the mainWindowController's split view. Herein lies the problem. When I instantiate each object in mainWindowController, I don't know if their views actually exist after the alloc/init call. In fact, I believe I should assume they do not yet exist. mainWindowController must add A and B to its split view and then create the autolayout constraints for both A and B, since they are relative to each other. So, in mainWindowController, how can I know when A and B have loaded their views so that I can add them to the split view and setup the proper autolayout constraints? I can think of some ways to implement this, but each solution is uglier than the last. What is the best practice here? As I mentioned, A and B will be creating their own subviews, etc, so this is a general problem I will have to deal with in this app. I appreciate any input!
Asked
by yoppeh.
Last updated .
Post marked as unsolved
39 Views

NSDiffableDataSourceSnapshot -> "deleteItems" does not work for cells that are collapsed

Hello. Please help me to solve the issue: NSDiffableDataSourceSnapshot - "deleteItems" does not work for cells that are collapsed. Also, func sectionIdentifier(containingItem identifier: ItemIdentifierType) - SectionIdentifierType? does not return "SectionIdentifierType" if we pass in a cell that has been collapsed. Please tell me, if I want to delete a cell in a section that is currently collapsed, how can I do this? Thanks.
Asked
Last updated .
Post marked as unsolved
323 Views

App crashing randomly - Not possible to remove variable

** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Not possible to remove variable: 400: unknown var (bug!) with engine as delegate:0x283c8ed40{id: 33112} colIndex:32 from engine NSISEngine: 0x129248130{ delegate:0x12934eaa0 EngineVars:  0: objective{id: 33102} rowIndex:0  1: UIImageView:0x12924ec90.Height{id: 32592} rowIndex:1073741824  2: 0x280a04be0.marker{id: 32591} colIndex:1073741825  3: UIImageView:0x12924ec90.Width{id: 32807} rowIndex:1  4: 0x280dc35a0.posErrorMarker{id: 32871} colIndex:1  5: 0x280dc35a0.negError{id: 32872} rowIndex:88  6: 0x280dc3d80.posErrorMarker{id: 32873} colIndex:1073741826  7: 0x280dc3d80.negError{id: 32874} rowIndex:1073741825  8: UIImageView:0x129353f00.Width{id: 32594} rowIndex:2  9: 0x280979d60.marker{id: 32593} colIndex:3 10: 0x280dc1e60.posErrorMarker{id: 32875} colIndex:4 11: 0x280dc1e60.negError{id: 32876} rowIndex:3 12: UIImageView:0x129353f00.Height{id: 32822} rowIndex:1073741826 13: 0x280dc39c0.posErrorMarker{id: 32877} colIndex:1073741827 14: 0x280dc39c0.negError{id: 32878} rowIndex:1073741898 15: UIButton:0x1293540d0.Width{id: 32817} rowIndex:4 16: 0x280dc2040.posErrorMarker{id: 32879} rowIndex:93 17: 0x280dc2040.negError{id: 32880} colIndex:6 18: UIButton:0x1293540d0.Height{id: 32820} rowIndex:1073741827 19: 0x280dc3de0.posErrorMarker{id: 32881} rowIndex:96 20: 0x280dc3de0.negError{id: 32882} colIndex:1073741830 21: UILabel:0x129353300.Width{id: 32811} rowIndex:5 22: 0x280dc3e40.posErrorMarker{id: 32883} colIndex:44 23: 0x280dc3e40.negError{id: 32884} rowIndex:90 24: UILabel:0x129353300.Height{id: 32842} colIndex:1073741828 25: 0x280dc27c0.posErrorMarker{id: 32885} colIndex:1073741831 26: 0x280dc27c0.negError{id: 32886} rowIndex:1073741828 27: UILabel:0x129353c90.Width{id: 32840} rowIndex:6 28: 0x280dc1da0.posErrorMarker{id: 32887} colIndex:9 29: 0x280dc1da0.negError{id: 32888} rowIndex:97 30: UILabel:0x129353c90.Height{id: 32829} colIndex:1073741832 31: 0x280dc31e0.posErrorMarker{id: 32889} colIndex:1073741833 32: 0x280dc31e0.negError{id: 32890} rowIndex:1073741900 33: UIImageView:0x12934e490.Width{id: 32596} rowIndex:1073741905 34: UIImageView:0x12934e490.Height{id: 32597} colIndex:1073741844 35: 0x280963a70.marker{id: 32595} colIndex:11 36: 0x280dc2ee0.posErrorMarker{id: 32891} colIndex:12 37: 0x280dc2ee0.negError{id: 32892} rowIndex:8 38: 0x280dc1d40.posErrorMarker{id: 32893} colIndex:1073741835 39: 0x280dc1d40.negError{id: 32894} rowIndex:1073741830 40: UIButton:0x1293543b0.Width{id: 32832} rowIndex:9 41: 0x280dc1440.posErrorMarker{id: 32895} colIndex:0 42: 0x280dc1440.negError{id: 32896} rowIndex:1073741845 43: UIButton:0x1293543b0.Height{id: 32827} rowIndex:1073741831 44: 0x280dc3840.posErrorMarker{id: 32897} colIndex:1073741836 45: 0x280dc3840.negError{id: 32898} rowIndex:1073741829 46: UILabel:0x129353a20.Width{id: 32848} rowIndex:10 and another thousand or so lines. this crash occurs after I change the language and open the workout page to start a workout immediately, and sometimes on the second time, I open the workout page.
Asked
by BibinAlex.
Last updated .
Post marked as unsolved
33 Views

ZStack: Empty Space at the end of the View

Hey, Whenever I add a frame modifier to ZStack(alignment: .topLeading) The view offsets to a negative value on the x-axis, I'm not sure why this is happening, I fixed it by removing .topLeading from alignment and the frame modifier. Does someone know the cause of this problem?
Asked
by Nav_07.
Last updated .
Post marked as unsolved
969 Views

iPhone with iOS 14 beta 2 doesn't autorotate when connected to XCode debugger

I have iPhone 11 Pro running iOS 14 beta 2. In one of my projects (and only that project perhaps), the view controller doesn't autorotate when connected to XCode (11 or 12) debugger. When not connected to debugger, there is no issue in autorotation. This happens for only one particular project and it's not clear what could be blocking autorotation. None of the autorotation methods are called. I wonder what could be blocking autorotation. And if I connect any iOS 13 device, autorotation works with the debugger. Is this a known issue with iOS 14/XCode?
Asked
by Devgeek.
Last updated .
Post marked as unsolved
147 Views

Warnings in NSCollectionView referencing UICollectionViewFlowLayout

Hi, I have an NSOutlineView, and each cell within that has an NSCollectionView (a horizontal one), setup using autolayout with the 'height' of the collectionView driving the height of the OutlineView cell. Each item in the collectionView can have a dynamic width, and I use a 'dummy' collectionView to size each item from it's contents, then getting the height of the collectionView and using a 'height constraint' to make each collectionView get the height it needs (and hence the cell have a dynamic height. It works fine for the most part, but I get this warning multiple times in the console: "The behavior of the UICollectionViewFlowLayout is not defined because: the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values. The relevant UICollectionViewFlowLayout instance is <NSCollectionViewFlowLayout: 0x10e3b7f80>, and it is attached to <MacTagsCustomCollectionView: 0x10e3b7840>. Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger." I've tried Googling this, but I can't find a good explanation for this issue. Also, I'm not sure why it references 'UICollectionViewFlowLayout' when it's an AppKit app and uses NSCollectionView. Also, setting the 'UICollectionViewFlowLayoutBreakForInvalidSizes' symbolic breakpoint doesn't help since it never gets triggered. Here is some code from my outlineView's viewForTableColumn, where I get the height of the collectionView and hence the height of the cell: result = [outlineView makeViewWithIdentifier:@"DataWithTags" owner:self]; if (result.tagListCollectionView.delegate == nil) { result.tagListCollectionView.delegate = self; result.tagListCollectionView.dataSource = self; result.tagsCollectionViewScrollView.automaticallyAdjustsContentInsets = NO; result.tagListCollectionView NSNib *cellNib = [[NSNib alloc] initWithNibNamed:@"MacTagsForPersonItem" bundle:nil]; [result.tagListCollectionView registerNib: cellNib forItemWithIdentifier:@"PersonTagsCollectionViewItemID"]; if (self.tagsSizingItem == nil) { NSArray *topLevelObjects; [cellNib instantiateWithOwner:self.tagsSizingItem topLevelObjects: &topLevelObjects]; for (id topLevelObject in topLevelObjects) { if ([topLevelObject isKindOfClass:[MacPersonTagsCollectionViewItem class]]) { self.tagsSizingItem = topLevelObject; break; } } } result.tagListCollectionView.backgroundColors = @[[NSColor clearColor]]; result.tagListCollectionView.enclosingScrollView.backgroundColor = [NSColor clearColor]; result.tagsCollectionViewScrollView.verticalScroller.hidden = YES; } result.tagListCollectionView.tagsPerson = person; [result.tagListCollectionView reloadData]; result.frame = outlineView.bounds; [result layoutSubtreeIfNeeded]; [result.tagListCollectionView layoutSubtreeIfNeeded]; if (person.tagsCacheHeight == 0) { &#9; person.tagsCacheHeight = result.tagListCollectionView.collectionViewLayout.collectionViewContentSize.height; } result.collectionViewHeightConstraint.constant = person.tagsCacheHeight; Anyone with any idea on how to overcome this? I feel that it's responsible for some layout issues that I'm having in the view.
Asked
by zulfishah.
Last updated .
Post marked as unsolved
708 Views

Strange UIButtonBarButton layout errors on all textView, fields and searchbars on iPad only

All of a sudden, all TextViews, TextFields and even searchbars give the same console error on entering them: (   "<NSAutoresizingMaskLayoutConstraint:0x281fe1b30 h=--& v=--& _UIButtonBarButton:0x1290c0cd0.height == 0  (active)>",   "<NSLayoutConstraint:0x281ffa440 V:|-(6)-[_UIUCBKBSelectionBackground:0x1290c14c0]  (active, names: '|':_UIButtonBarButton:0x1290c0cd0 )>",   "<NSLayoutConstraint:0x281ffa3a0 _UIUCBKBSelectionBackground:0x1290c14c0.bottom == _UIButtonBarButton:0x1290c0cd0.bottom - 6  (active)>" ) Happens on iPads only (simulator too). My app is a universal app, programmatic UI (UIKit). iPhones are perfectly fine. Happened all of a sudden two days ago. Could this be because of upgrades to 14.2 both simulator and devices and relevant Xcode updates? I have no clue whatsoever where this comes from and how to remove it ... EDIT Starting to think this has something to do with the keyboards on iPads?
Asked
Last updated .
Post marked as unsolved
70 Views

How to use NSUserInterfaceCompression

I've create a custom cocoa control (subclassed NSView) that can show in two display modes: compressed, expanded . I'd like to be able to use NSUserInterfaceCompression but can find no relevant documentation or examples on how to make it behave as the built-in segment control, which collapses into a minimum-size when the window is resized.
Asked
by Smithers.
Last updated .
Post marked as unsolved
80 Views

NSTextView in NSScrollView with magnification crashes on resize

I have an NSTextView inside an NSScrollView with magnification. Zooming in with a pinch-and-zoom gesture works fine, but if I then resize the window while zoomed in, it will eventually crash with the error The window has been marked as needing another Display Window pass, but it has already had more Display Window passes than there are views in the window. It does not always happen immediately, sometimes you have to keep resizing for a while to trigger it. I have made a video illustrating the problem here: youtu.be/M_JRQI2oDaY The original code is here: https://github.com/angstsmurf/spatterlight/tree/helpviewtest (The branch helpviewtest is a cut down test case created for this problem.)
Asked
by Dalaplan.
Last updated .
Post marked as unsolved
107 Views

UITableView viewForHeaderInSection messed up the header view on iOS 14

I am having a UITableView and it has a custom view as its section header. The UI looks fine on all previous versions except iOS 14. on iOS 14 the HeaderView subviews are all messed up completely and scattered/squeezed in the header view. We are using Objective-C Auto Resizing Masks for all the Custom Views present in the table view header. is there any API changes made in iOS 14 regards with Auto Resizing Mask/TableView/Auto Layout. Wanted to know why the UI is behaving weird in iOS 14 and working great on the previous versions. This issue is happening both on Simulator and on Real Device as well.
Asked
Last updated .
Post marked as solved
2.7k Views

Disable keyboard avoidance for SwiftUI view

I'm having trouble disabling keyboard avoidance for a SwiftUI view that is embedded in a UIHostingController. When the UITextField becomes first responder, the SwiftUI view jumps out of the way for the keyboard, and I want it to stay in place. To test this out, set the ViewController as the rootViewController in a UIKit App Delegate. import SwiftUI struct ContentView: View {     var body: some View {         Text("I want this text to stay put.") /* THIS DOESN'T WORK         .ignoresSafeArea(.keyboard) */     } } class ViewController: UIViewController {     override func viewDidLoad() {         super.viewDidLoad()         let textField = UITextField(frame: CGRect(x: 10, y: 100, width: 200, height: 50))         textField.backgroundColor = .white         textField.placeholder = "Tap here!"         view.addSubview(textField)         let button = UIButton(type: .system, primaryAction: UIAction(title: "Dismiss Keyboard", handler: { _ in             textField.resignFirstResponder()         }))         button.frame = CGRect(x: 220, y: 100, width: 140, height: 50)         view.addSubview(button)         let hostingController = UIHostingController(rootView: ContentView())         hostingController.view.frame = CGRect(x: 10, y: UIScreen.main.bounds.size.height - 510, width: UIScreen.main.bounds.size.width - 20, height: 500)         view.addSubview(hostingController.view)     } }
Asked
Last updated .
Post marked as unsolved
186 Views

Debugger info - how to interpret and rectify and App submission

Hope someone can offer some guidance for me please. I have an app that runs to my simulators and iPhone devices fine, but with the following error in the debugger. I have a few questions... apologies, am pretty new to this development stuff. 1 - There's so much info here. How do I identify which constraint to check here to find the source of the issue? 2 - Would an issue such as this cause any submission to the App Store to fail? Thanks folks. language 2021-02-26 16:54:51.252513+0000 name[44594:2610742] [LayoutConstraints] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want.  Try this:  (1) look at each constraint and try to figure out which you don't expect;  (2) find the code that added the unwanted constraint or constraints and fix it.  (     "NSLayoutConstraint:0x600002c9c780 'BIB_Trailing_CB_Leading' H:[_UIModernBarButton:0x7f932142d310]-(6)-[_UIModernBarButton:0x7f932142b070'Featured']   (active)",     "NSLayoutConstraint:0x600002c9c7d0 'CB_Trailing_Trailing' _UIModernBarButton:0x7f932142b070'Featured'.trailing = BackButton.trailing   (active, names: BackButton:0x7f932142a760 )",     "NSLayoutConstraint:0x600002c9d6d0 'UINav_static_button_horiz_position' _UIModernBarButton:0x7f932142d310.leading == UILayoutGuide:0x6000036b32c0'UIViewLayoutMarginsGuide'.leading   (active)",     "NSLayoutConstraint:0x600002c9d720 'UINavItemContentGuide-leading' H:[BackButton]-(0)-[UILayoutGuide:0x6000036b33a0'UINavigationBarItemContentLayoutGuide']   (active, names: BackButton:0x7f932142a760 )",     "NSLayoutConstraint:0x600002ca7e80 'UINavItemContentGuide-trailing' UILayoutGuide:0x6000036b33a0'UINavigationBarItemContentLayoutGuide'.trailing == _UINavigationBarContentView:0x7f932140ee40.trailing   (active)",     "NSLayoutConstraint:0x600002c9dea0 'UIView-Encapsulated-Layout-Width' _UINavigationBarContentView:0x7f932140ee40.width == 0   (active)",     "NSLayoutConstraint:0x600002c90230 'UIView-leftMargin-guide-constraint' H:|-(0)-[UILayoutGuide:0x6000036b32c0'UIViewLayoutMarginsGuide'](LTR)   (active, names: '|':_UINavigationBarContentView:0x7f932140ee40 )" ) Will attempt to recover by breaking constraint  NSLayoutConstraint:0x600002c9c780 'BIB_Trailing_CB_Leading' H:[_UIModernBarButton:0x7f932142d310]-(6)-[_UIModernBarButton:0x7f932142b070'Featured']   (active) Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in UIKitCore/UIView.h may also be helpful. code-block
Asked
Last updated .
Post marked as unsolved
205 Views

UICollectionViewCompositionalLayout unexpected behavior with .estimated heights

Using NSCollectionLayoutSize with .estimated dimensions in horizontal orthogonal sections, creates layout issues. The cells &amp; supplementary views have layout conflicts, the scroll behavior is sub optimal and spacing is not as expected Working with Xcode: 12.4 , Simulator: iOS 14.4 Layout bug: [LayoutConstraints] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. ( "NSLayoutConstraint:0x6000011266c0 UIView:0x7fc6c4617020.height == 80 (active)", "NSLayoutConstraint:0x600001126530 V:|-(0)-[UIView:0x7fc6c4617020] (active, names: '|':UIView:0x7fc6c4616d10 )", "NSLayoutConstraint:0x6000011261c0 UIView:0x7fc6c4617020.bottom == UIView:0x7fc6c4616d10.bottom (active)", "NSLayoutConstraint:0x600001121360 'UIView-Encapsulated-Layout-Height' UIView:0x7fc6c4616d10.height == 50 (active)" ) Will attempt to recover by breaking constraint NSLayoutConstraint:0x6000011266c0 UIView:0x7fc6c4617020.height == 80 (active) Code to reproduce: import UIKit class ViewController: UIViewController { lazy var collectionView: UICollectionView = { let layout = createLayout() let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.dataSource = self collectionView.backgroundColor = .systemBackground collectionView.register(Cell.self, forCellWithReuseIdentifier: "cell") collectionView.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header") return collectionView }() private func createLayout() - UICollectionViewCompositionalLayout { let sectionProvider = { (section: Int, layoutEnvironment: NSCollectionLayoutEnvironment) - NSCollectionLayoutSection? in return self.horizontalLayout(layoutEnvironment: layoutEnvironment) } let config = UICollectionViewCompositionalLayoutConfiguration() config.interSectionSpacing = 8 let layout = UICollectionViewCompositionalLayout(sectionProvider: sectionProvider, configuration: config) return layout } private func supplementaryHeader() - NSCollectionLayoutBoundarySupplementaryItem { let titleSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(50)) let titleSupplementary = NSCollectionLayoutBoundarySupplementaryItem( layoutSize: titleSize, elementKind: UICollectionView.elementKindSectionHeader, alignment: .top) return titleSupplementary } private func horizontalLayout(layoutEnvironment: NSCollectionLayoutEnvironment) - NSCollectionLayoutSection { let size = NSCollectionLayoutSize(widthDimension: .estimated(120), heightDimension: .estimated(50)) let item = NSCollectionLayoutItem(layoutSize: size) let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitems: [item]) let section = NSCollectionLayoutSection(group: group) section.orthogonalScrollingBehavior = .continuous section.interGroupSpacing = 8 section.contentInsets = NSDirectionalEdgeInsets(top: 16, leading: 16, bottom: 16, trailing: 16) section.boundarySupplementaryItems = [supplementaryHeader()] return section } override func viewDidLoad() { super.viewDidLoad() view.addSubview(collectionView) NSLayoutConstraint.activate([ collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), collectionView.topAnchor.constraint(equalTo: view.topAnchor), collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } } // MARK: UICollectionViewDataSource extension ViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) - UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) return cell } func numberOfSections(in collectionView: UICollectionView) - Int { return 25 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) - Int { return 4 } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) - UICollectionReusableView { switch kind { case UICollectionView.elementKindSectionHeader: let header: HeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header", for: indexPath) as! HeaderView return header default: fatalError() } } } class Cell: UICollectionViewCell { lazy var view: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .systemRed return view }() override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("not implemented") } func configure() { contentView.addSubview(view) view.heightAnchor.constraint(equalToConstant: 80).isActive = true view.widthAnchor.constraint(equalToConstant: 100).isActive = true NSLayoutConstraint.activate([ view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), view.topAnchor.constraint(equalTo: contentView.topAnchor), view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor) ]) } } class HeaderView: UICollectionReusableView { lazy var view: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .systemTeal return view }() override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("not implemented") } func configure() { addSubview(view) view.heightAnchor.constraint(equalToConstant: 60).isActive = true NSLayoutConstraint.activate([ view.leadingAnchor.constraint(equalTo: self.leadingAnchor), view.trailingAnchor.constraint(equalTo: self.trailingAnchor), view.topAnchor.constraint(equalTo: self.topAnchor), view.bottomAnchor.constraint(equalTo: self.bottomAnchor) ]) } }
Asked
by papanton.
Last updated .
Post marked as unsolved
216 Views

Xcode simulator/device layout problem

Hello everyone. I recently made my own app and released it to app store. Before I released it, I use my device(IPhone 7), and use various simulator on xcode to find out there are no layout problems. When I run my app on IPhone 7 and simulator(IPhone 11 pro, IPhone 12...), it worked great. But when real customer downloaded my app through app store, they found out there are layout problem, such as no text on button, white screen things.(They use IPhone 12 or IPhone 11) The problem is that I only have Iphone 7, and when I tested it through my device, there was no problem at all. And simulator also didn't show any problem on layout. So how can I test my app to assure that there are no layout problem? Do I have to buy another device like IPhone 12? Why there is difference between simulator and device on UI layout? Thanks for reading.
Asked
Last updated .
Post marked as unsolved
166 Views

Dynamically Sized View based on Child View Controller using systemLayoutSizeFitting

I have a child view controller as follows: class ChildViewControllerAAA: UIViewController {          override func viewDidLoad() {         super.viewDidLoad()         view.backgroundColor = .green                  let newView = UIView()         view.addSubview(newView)         newView.backgroundColor = .systemBlue         newView.translatesAutoresizingMaskIntoConstraints = false                  NSLayoutConstraint.activate([             newView.topAnchor.constraint(equalTo: view.topAnchor),             newView.leadingAnchor.constraint(equalTo: view.leadingAnchor),             newView.trailingAnchor.constraint(equalTo: view.trailingAnchor),             newView.heightAnchor.constraint(equalToConstant: 123),         ])     }               override func viewDidLayoutSubviews() {         super.viewDidLayoutSubviews()         calculatePreferredSize()     }               func calculatePreferredSize() {         let targetSize = CGSize(width: view.bounds.width,                                 height: UIView.layoutFittingCompressedSize.height)         preferredContentSize = view.systemLayoutSizeFitting(targetSize)     } } The above works fine and if I instantiate the above view controller full screen, it works fine. But if I then try to embed the above in another view controller and use it as a child view controller, the embedded blue UIView newView does not work correctly and I get broken constraints with the height of newView being broken by the Auto Layout engine. This is the code where I add it as a child VC: class ViewController: UIViewController {          var container : UIView!     var childVC   : ChildViewController!          var containerHeightConstraint: NSLayoutConstraint!          override func viewDidLoad() {         super.viewDidLoad()                  view.backgroundColor = .purple                  container = UIView()         container.backgroundColor = .systemPink         container.translatesAutoresizingMaskIntoConstraints = false                  view.addSubview(container)         container.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true         container.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true         container.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true                  containerHeightConstraint = NSLayoutConstraint()         containerHeightConstraint = container.heightAnchor.constraint(equalToConstant: 0)         containerHeightConstraint.isActive = true                  childVC = ChildViewController()         addChild(childVC)         container.addSubview(childVC.view)         childVC.view.frame = container.bounds         childVC.didMove(toParent: self)         childVC.view.translatesAutoresizingMaskIntoConstraints = false     }               override func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer) {         super.preferredContentSizeDidChange(forChildContentContainer: container)         if (container as? ChildViewControllerAAA) != nil {             containerHeightConstraint.constant = container.preferredContentSize.height         }     } } What I'm trying to work out, using the systemLayoutSizeFitting with UIView.layoutFittingCompressedSize is get back the minimum required size of the child view and then constrain it to bottom of the parent view controller. So in this mockup, it should only be 123 high.
Asked
by anthonycj.
Last updated .