Auto Layout

RSS for tag

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

Posts under Auto Layout tag

111 Posts

Post

Replies

Boosts

Views

Activity

Creating square views regardless of orientation
I am trying to create a UIView within a UIStackView that I want to always be square regardless of device and orientation. I have seen posting that explain how others have done it (setting constraints between UIView and superview for both height and width - a required set and an optional set - along with a 1:1 aspect constraint for the UIView) , but it no longer seems to work under all instances - in particular iPad and iPhone 11s. Does anyone have any advice on how to make this happen. It seems to me to be a pretty routine thing to do. I've done it before programmatically, but I would really like to get it done within Interface Builder. Any suggestions would be greatly appreciated.
1
0
2.1k
Nov ’21
Why does NSStackView prevent resizing of parent view/window?
I'm implementing a horizontal NSStackView with child views of varying size. The stack view should resize horizontally with its parent view, which in turn resizes with the window. I expect the stack view's arranged distribution (fill proportionally) to adjust the distribution of child views as its width changes. I keep hitting the bizarre behavior where the window can't be resized horizontally at all - the vertical/diagonal resize cursors no longer appear, and the window can only be resized vertically. The problem is not that the child view doesn't resize with the window: the child view actually prevents resizing of the window! I first saw this creating an empty NSStackView and adding it to its parent view in code, with layout constraints (top, leading, trailing; also tried width). I tried messing with constraint priorities but that did not correct the issue. (With the stack view not there, its parent view resizes with the window just fine). When I created the NSStackView in the .xib this problem went away, the empty NSStackView resizes horizontally along with its parent, so that's what I'm doing now. However, now when I add a set of arranged subviews in code, it happens again - they are distributed perfectly, but the window again cannot be horizontally resized! The subviews are minimal NSView implementations (drawing their bounds); they do not have intrinsic size. They do each have child NSTextField labels, with autolayout constraints to horizontally resize along with their parents. There are no constraints besides those internal to each child view and its label subview. What am I not understanding about AutoLayout and NSStackView? I cannot imagine an intentional design that would break the user's ability to resize the window in one direction based on anything an NSStackView does, but that's exactly what happens.
1
0
2.5k
Oct ’21
Resize image with autolayout
My app loads an image at runtime and I want to display it inside a table cell. To do that I created a UIView (trailing/leading/top/bottom: 10) inside the cell and added a UIImageView as its child. What constraints do I need for the child, so the image keeps its proper aspect ration, isn't wider than the width of the screen and there's no unused space (apart from the constraints)? I tried to use: Trailing/leading/top/bottom: 0 Align center x/y This works if the image uses the portrait format but with landscape there's unused space above and below the image. I also tried to set the view's height to ">=50" but no success and I can't just set a max. value because my app has to work on both iPhones and iPads.
2
0
1.7k
Oct ’21
Ambiguous layout warnings after Xcode 13.0 upgrade
Hi. My 2 years old project shows ambiguous layout warnings after installing Xcode 13.0. The warnings are basically nuisance (layout shows correctly in the app). All the warnings refer to constraints of objects inside a tableview. The warnings start only after cell 16 downwards (distributed across 4 sections, S1: 2 cells, S2: 2 cells, S3: 1 cells, S4: 12 cells, ...). Hence my idea, if there is any limit to the number of cells Xcode 13.0 can handle? Previous Xcode didn't have any (!) issues regarding this portion of the layout. The screenshots just show an example of such a nuisance warning. Any ideas? Thanks.
2
0
1.2k
Oct ’21
Potential bug with "Unable to activate constraint with anchors"
The ios app I am currently developing starts off on a login screen which then presents the next view controller via a login button. Upon moving on to the next VC I get the error: Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <NSLayoutYAxisAnchor:0x600000d0af40 "UIStackView:0x7fe87df14160.top"> and <NSLayoutYAxisAnchor:0x600000d0ad40 "UILayoutGuide:0x600002102300'UIViewSafeAreaLayoutGuide'.bottom"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.' Here is the relevant VC code for the contoller being showed: class LocationSelectViewController: UIViewController {       let promptLabel: UILabel = {     let label = UILabel()           label.translatesAutoresizingMaskIntoConstraints = false     label.text = "Enter Your Location`s \nAddress"     label.font = .boldSystemFont(ofSize: 23)     label.numberOfLines = 0     label.preferredMaxLayoutWidth = label.frame.width     label.textAlignment = .center           return label   }()       let streetAddressField: UITextField = {     let textField = UITextField()         textField.translatesAutoresizingMaskIntoConstraints = false     textField.placeholder = "street address"     textField.borderStyle = .roundedRect     textField.textAlignment = .left         return textField   }()       let cityField: UITextField = {     let textField = UITextField()         textField.translatesAutoresizingMaskIntoConstraints = false     textField.placeholder = "city"     textField.borderStyle = .roundedRect     textField.textAlignment = .left         return textField   }()       let stateField: UITextField = {     let textField = UITextField()         textField.translatesAutoresizingMaskIntoConstraints = false     textField.placeholder = "state"     textField.borderStyle = .roundedRect     textField.textAlignment = .left         return textField   }()       let saveButton: UIButton = {     let button = UIButton(type: .system)     button.setTitle("Add Location", for: .normal)     button.translatesAutoresizingMaskIntoConstraints = false           return button   }()       var currentUser: User?   let geocoder = CLGeocoder()   override func viewDidLoad() {     super.viewDidLoad()           view.backgroundColor = .white           let stackView = UIStackView()           let views: [UIView] = [streetAddressField, cityField, stateField]           stackView.axis = .vertical     stackView.spacing = 17     stackView.translatesAutoresizingMaskIntoConstraints = false           view.addSubview(promptLabel)     view.addSubview(stackView)     view.addSubview(saveButton)           for view in views {       stackView.addArrangedSubview(view)     }           let constraintsArray: [NSLayoutConstraint] = [promptLabel.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), promptLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 30), promptLabel.heightAnchor.constraint(lessThanOrEqualToConstant: 70), stackView.topAnchor.constraint(equalTo: promptLabel.bottomAnchor, constant: 40), stackView.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), stackView.widthAnchor.constraint(equalToConstant: 300), saveButton.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), saveButton.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: 30)]           saveButton.addTarget(self, action: #selector(addLocationTouchUpInside), for: .touchUpInside)           NSLayoutConstraint.activate(constraintsArray)   } Also I am aware that the constraints are hard to read so they are listed below promptLabel.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), promptLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 30), promptLabel.heightAnchor.constraint(lessThanOrEqualToConstant: 70), stackView.topAnchor.constraint(equalTo: promptLabel.bottomAnchor, constant: 40), stackView.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), stackView.widthAnchor.constraint(equalToConstant: 300), saveButton.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), saveButton.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: 30) I orginally asked this question on SO which has lead me to believe this is a potential bug. I likely could hold off or workaround the issue by rewriting/choosing different constraints, but if its a bug I would much rather not put in pointless work.
1
0
2.5k
Oct ’21
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) ]) } }
5
1
4.8k
Oct ’21
Why is the layout in SwiftUI so poorly designed by a zillion dollar company. .
This is really a post (dig at) to the SwiftUI designers. I have been a developer in many many different languages for far too many years. Over the last 20 I have done a lot of web (browser) development. From the web developer perspective, developing applications that behave correctly in any browser has been a really big thing for probably more than 20 years. I even remember doing it in tables. We are now at a stage where it does work now (mostly). Frameworks like Twitter Bootstrap work really well and so do a lot of others. Their basic mission is that a page (view) will work no matter what the resolution (even those we don’t have yet) in an ever changing ‘view’ world. Yet I now come to SwiftUI… Lots of tell us your device and get your graphic designer to produce a zillion graphics for each (noting he / she isn’t a fortune teller, so they do not know what’s coming next. After playing for days with GeometryReader and UIScreen.main.bounds (hell will that even be supported in the future) I’m not impressed. I don’t understand why something that has been analysed and pretty much put to bed in the ‘web’ world is now attempting to be reinvented really really really really badly. I even attempted to fix this issue with UIKit but even that wasn’t much better.  Why is a company with so much money and so many resources trying to reinvent the wheel? I don’t get it. So much so I’m starting to tell my clients (big ones) to ditch Apple and go down far easier roots. I doubt any of the SwiftUI compiler developers even read this stuff. But hey if you do, it’s time for a reality check… If they don’t ha ha ha ha I rest my case.
0
0
632
Oct ’21
Standard value for Auto Layout constraints
Hello! I am new to iOS development and was walking through UIKit iOS App Dev Tutorial on this website. My problems start every time when I need to set leading horizontal spacing to "Standard" by removing value or selecting it in the dropdown menu. When I try to do that, the value in the field resets to previously set value and "Use Standard value" is greyed out. This is so frustrating! Even when I download complete project and try to set value myself, it still does not work! Is it an Xcode bug? My version is 13.0 (13A233)
3
0
1.5k
Oct ’21
Screen becomes unresponsive during game
Hello! I am having trouble with my quiz game - sometimes (not always) after completing a level, the screen darkens and the game becomes unresponsive. I am unable to click anywhere on the screen. I've been scratching my head about this issue for several weeks now and can't get to the bottom of it. I'd really appreciate some help/advice on the matter if anyone knows that's wrong. I've attached the error log as it was too long to add here. Many thanks, Ermes Error log:
1
0
2.2k
Sep ’21
Creating square views regardless of orientation
I am trying to create a UIView within a UIStackView that I want to always be square regardless of device and orientation. I have seen posting that explain how others have done it (setting constraints between UIView and superview for both height and width - a required set and an optional set - along with a 1:1 aspect constraint for the UIView) , but it no longer seems to work under all instances - in particular iPad and iPhone 11s. Does anyone have any advice on how to make this happen. It seems to me to be a pretty routine thing to do. I've done it before programmatically, but I would really like to get it done within Interface Builder. Any suggestions would be greatly appreciated.
Replies
1
Boosts
0
Views
2.1k
Activity
Nov ’21
UILabel with superscript text
How can make a UILabel look this way in Xcode12?
Replies
2
Boosts
0
Views
2.9k
Activity
Nov ’21
Why does NSStackView prevent resizing of parent view/window?
I'm implementing a horizontal NSStackView with child views of varying size. The stack view should resize horizontally with its parent view, which in turn resizes with the window. I expect the stack view's arranged distribution (fill proportionally) to adjust the distribution of child views as its width changes. I keep hitting the bizarre behavior where the window can't be resized horizontally at all - the vertical/diagonal resize cursors no longer appear, and the window can only be resized vertically. The problem is not that the child view doesn't resize with the window: the child view actually prevents resizing of the window! I first saw this creating an empty NSStackView and adding it to its parent view in code, with layout constraints (top, leading, trailing; also tried width). I tried messing with constraint priorities but that did not correct the issue. (With the stack view not there, its parent view resizes with the window just fine). When I created the NSStackView in the .xib this problem went away, the empty NSStackView resizes horizontally along with its parent, so that's what I'm doing now. However, now when I add a set of arranged subviews in code, it happens again - they are distributed perfectly, but the window again cannot be horizontally resized! The subviews are minimal NSView implementations (drawing their bounds); they do not have intrinsic size. They do each have child NSTextField labels, with autolayout constraints to horizontally resize along with their parents. There are no constraints besides those internal to each child view and its label subview. What am I not understanding about AutoLayout and NSStackView? I cannot imagine an intentional design that would break the user's ability to resize the window in one direction based on anything an NSStackView does, but that's exactly what happens.
Replies
1
Boosts
0
Views
2.5k
Activity
Oct ’21
Resize image with autolayout
My app loads an image at runtime and I want to display it inside a table cell. To do that I created a UIView (trailing/leading/top/bottom: 10) inside the cell and added a UIImageView as its child. What constraints do I need for the child, so the image keeps its proper aspect ration, isn't wider than the width of the screen and there's no unused space (apart from the constraints)? I tried to use: Trailing/leading/top/bottom: 0 Align center x/y This works if the image uses the portrait format but with landscape there's unused space above and below the image. I also tried to set the view's height to ">=50" but no success and I can't just set a max. value because my app has to work on both iPhones and iPads.
Replies
2
Boosts
0
Views
1.7k
Activity
Oct ’21
Ambiguous layout warnings after Xcode 13.0 upgrade
Hi. My 2 years old project shows ambiguous layout warnings after installing Xcode 13.0. The warnings are basically nuisance (layout shows correctly in the app). All the warnings refer to constraints of objects inside a tableview. The warnings start only after cell 16 downwards (distributed across 4 sections, S1: 2 cells, S2: 2 cells, S3: 1 cells, S4: 12 cells, ...). Hence my idea, if there is any limit to the number of cells Xcode 13.0 can handle? Previous Xcode didn't have any (!) issues regarding this portion of the layout. The screenshots just show an example of such a nuisance warning. Any ideas? Thanks.
Replies
2
Boosts
0
Views
1.2k
Activity
Oct ’21
Potential bug with "Unable to activate constraint with anchors"
The ios app I am currently developing starts off on a login screen which then presents the next view controller via a login button. Upon moving on to the next VC I get the error: Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <NSLayoutYAxisAnchor:0x600000d0af40 "UIStackView:0x7fe87df14160.top"> and <NSLayoutYAxisAnchor:0x600000d0ad40 "UILayoutGuide:0x600002102300'UIViewSafeAreaLayoutGuide'.bottom"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.' Here is the relevant VC code for the contoller being showed: class LocationSelectViewController: UIViewController {       let promptLabel: UILabel = {     let label = UILabel()           label.translatesAutoresizingMaskIntoConstraints = false     label.text = "Enter Your Location`s \nAddress"     label.font = .boldSystemFont(ofSize: 23)     label.numberOfLines = 0     label.preferredMaxLayoutWidth = label.frame.width     label.textAlignment = .center           return label   }()       let streetAddressField: UITextField = {     let textField = UITextField()         textField.translatesAutoresizingMaskIntoConstraints = false     textField.placeholder = "street address"     textField.borderStyle = .roundedRect     textField.textAlignment = .left         return textField   }()       let cityField: UITextField = {     let textField = UITextField()         textField.translatesAutoresizingMaskIntoConstraints = false     textField.placeholder = "city"     textField.borderStyle = .roundedRect     textField.textAlignment = .left         return textField   }()       let stateField: UITextField = {     let textField = UITextField()         textField.translatesAutoresizingMaskIntoConstraints = false     textField.placeholder = "state"     textField.borderStyle = .roundedRect     textField.textAlignment = .left         return textField   }()       let saveButton: UIButton = {     let button = UIButton(type: .system)     button.setTitle("Add Location", for: .normal)     button.translatesAutoresizingMaskIntoConstraints = false           return button   }()       var currentUser: User?   let geocoder = CLGeocoder()   override func viewDidLoad() {     super.viewDidLoad()           view.backgroundColor = .white           let stackView = UIStackView()           let views: [UIView] = [streetAddressField, cityField, stateField]           stackView.axis = .vertical     stackView.spacing = 17     stackView.translatesAutoresizingMaskIntoConstraints = false           view.addSubview(promptLabel)     view.addSubview(stackView)     view.addSubview(saveButton)           for view in views {       stackView.addArrangedSubview(view)     }           let constraintsArray: [NSLayoutConstraint] = [promptLabel.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), promptLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 30), promptLabel.heightAnchor.constraint(lessThanOrEqualToConstant: 70), stackView.topAnchor.constraint(equalTo: promptLabel.bottomAnchor, constant: 40), stackView.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), stackView.widthAnchor.constraint(equalToConstant: 300), saveButton.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), saveButton.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: 30)]           saveButton.addTarget(self, action: #selector(addLocationTouchUpInside), for: .touchUpInside)           NSLayoutConstraint.activate(constraintsArray)   } Also I am aware that the constraints are hard to read so they are listed below promptLabel.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), promptLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 30), promptLabel.heightAnchor.constraint(lessThanOrEqualToConstant: 70), stackView.topAnchor.constraint(equalTo: promptLabel.bottomAnchor, constant: 40), stackView.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), stackView.widthAnchor.constraint(equalToConstant: 300), saveButton.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), saveButton.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: 30) I orginally asked this question on SO which has lead me to believe this is a potential bug. I likely could hold off or workaround the issue by rewriting/choosing different constraints, but if its a bug I would much rather not put in pointless work.
Replies
1
Boosts
0
Views
2.5k
Activity
Oct ’21
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) ]) } }
Replies
5
Boosts
1
Views
4.8k
Activity
Oct ’21
Why is the layout in SwiftUI so poorly designed by a zillion dollar company. .
This is really a post (dig at) to the SwiftUI designers. I have been a developer in many many different languages for far too many years. Over the last 20 I have done a lot of web (browser) development. From the web developer perspective, developing applications that behave correctly in any browser has been a really big thing for probably more than 20 years. I even remember doing it in tables. We are now at a stage where it does work now (mostly). Frameworks like Twitter Bootstrap work really well and so do a lot of others. Their basic mission is that a page (view) will work no matter what the resolution (even those we don’t have yet) in an ever changing ‘view’ world. Yet I now come to SwiftUI… Lots of tell us your device and get your graphic designer to produce a zillion graphics for each (noting he / she isn’t a fortune teller, so they do not know what’s coming next. After playing for days with GeometryReader and UIScreen.main.bounds (hell will that even be supported in the future) I’m not impressed. I don’t understand why something that has been analysed and pretty much put to bed in the ‘web’ world is now attempting to be reinvented really really really really badly. I even attempted to fix this issue with UIKit but even that wasn’t much better.  Why is a company with so much money and so many resources trying to reinvent the wheel? I don’t get it. So much so I’m starting to tell my clients (big ones) to ditch Apple and go down far easier roots. I doubt any of the SwiftUI compiler developers even read this stuff. But hey if you do, it’s time for a reality check… If they don’t ha ha ha ha I rest my case.
Replies
0
Boosts
0
Views
632
Activity
Oct ’21
How to create a self sizing collectionview cell with uicompositionallayout
Hi! How can I create a self sizing collectionview cells in section via UiCollectionViewCompositionalLayout? Thanks!
Replies
0
Boosts
0
Views
1k
Activity
Oct ’21
Standard value for Auto Layout constraints
Hello! I am new to iOS development and was walking through UIKit iOS App Dev Tutorial on this website. My problems start every time when I need to set leading horizontal spacing to "Standard" by removing value or selecting it in the dropdown menu. When I try to do that, the value in the field resets to previously set value and "Use Standard value" is greyed out. This is so frustrating! Even when I download complete project and try to set value myself, it still does not work! Is it an Xcode bug? My version is 13.0 (13A233)
Replies
3
Boosts
0
Views
1.5k
Activity
Oct ’21
Screen becomes unresponsive during game
Hello! I am having trouble with my quiz game - sometimes (not always) after completing a level, the screen darkens and the game becomes unresponsive. I am unable to click anywhere on the screen. I've been scratching my head about this issue for several weeks now and can't get to the bottom of it. I'd really appreciate some help/advice on the matter if anyone knows that's wrong. I've attached the error log as it was too long to add here. Many thanks, Ermes Error log:
Replies
1
Boosts
0
Views
2.2k
Activity
Sep ’21