I am building my UI from code and need to present another view controller as a popover, over the current controller. The popover will act as a modal dialog and will use about 50% of the screen size. The contents of the popover must be constrained in the screen center and support device rotation.
My initial implementation was done in viewDidLoad() of the PopoverController class and it worked as expected. However, I do not want view code in my controllers. After moving the popover view to a separate file, the fun began; auto layout and device rotation no longer worked as expected.
I have made a basic app showcasing this. The main controller has a button for displaying the popover. The popover has yellow background and should display a blue view in the center.
MainViewController :: Test button for displaying the popover
#objc func boxButtonTapped() {
let vc = PopoverController()
vc.modalPresentationStyle = .overCurrentContext
vc.modalTransitionStyle = .crossDissolve
present(vc, animated: true, completion: nil)
}
Popover Controller
class PopoverController: UIViewController {
var popoverView = PopoverView()
override func viewDidLoad() {
super.viewDidLoad()
}
override func loadView() {
view = popoverView
}
}
Popover View
class PopoverView: UIView {
let blueBox: UIView = {
let bb = UIView()
bb.backgroundColor = .blue
//bb.frame.size = CGSize(width: 100, height: 100)
bb.translatesAutoresizingMaskIntoConstraints = false
return bb
}()
override init(frame: CGRect) {
super.init(frame: frame)
createSubViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
createSubViews()
}
func createSubViews() {
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = .yellow
addSubview(blueBox)
blueBox.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
blueBox.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
blueBox.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.7).isActive = true
blueBox.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.4).isActive = true
}
}
When running the above code, the popover doesn`t even display! This is my first question, can anyone see why?
If I change translatesAutoresizingMaskIntoConstraints = false to true. Then the popover displays, but it does not resize when the device rotates. I do not know why and I don´t understand why translatesAutoresizingMaskIntoConstraints needs to be set to true in order for the view to display in the first place.
There must be a simple solution for such a trivial task. I have tried so many different approaches and listing them here would be impossible. I am new to IOS dev and Swift and I really would like to get a good start with clean code. Thank you for your time!
Update
I published the sample project on GitHub. So if you have the time and want a challenge/prove a concept then here it is: https://github.com/igunther/CleanController
If you are not adding constraints yourself - which, in this case, you are not - you still need to tell the view how to behave.
Change your createSubviews() function to this:
func createSubViews() {
//translatesAutoresizingMaskIntoConstraints = false
autoresizingMask = [.flexibleHeight, .flexibleWidth]
backgroundColor = .yellow
addSubview(blueBox)
blueBox.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
blueBox.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
blueBox.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.7).isActive = true
blueBox.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.4).isActive = true
}
That will allow auto-layout to re-layout your view(s) on device rotation.
According to Apple docs for translatesAutoresizingMaskIntoCon
If this property’s value is true, the system creates a set of constraints that duplicate the behavior specified by the view’s autoresizing mask.
and
By default, the property is set to true for any view you programmatically create. If you add views in Interface Builder, the system automatically sets this property to false.
My guess is that when set to false it's looking for constraints that don't exist.
As far as the rotation goes, you could put shouldAutorotate property in your VC?
Related
Problem
I have a custom UIView that has an image and selection (border) subview. I want to be able to add this custom UIView as a subview of a larger blank view. Here's the catch, the larger blank view needs to clip all of the subviews to its bounds (clipToBounds). However, the user can select one of the custom UIViews within the large blank view, where the subview is then highlighted by a border.
The problem is that because the large blank view clips to bounds, the outline for the selected subview is cut off.
I want the image in the subview to clip to the bounds of the large blank view, but still be able to see the full selection outline of the subview (which is cut off due to the large blank view's corner radius.
I am using UIKit and Swift
👎 What I Currently Have:
👍 What I Want:
The image part of the subview clips to the bounds (corner radius) of the large blank view, but the outline selection view in the subview should not.
Thanks in advance for all your help!
I think what you are looking for is not technically possible as defined by the docs
From the docs:
clipsToBounds
Setting this value to true causes subviews to be clipped to the bounds of the receiver. If set to false, subviews whose frames extend beyond the visible bounds of the receiver are not clipped. The default value is false.
So the subviews do not have control of whether they get clipped or not, it's the container view that decides.
So I believe Matic's answer is right in that the structure he proposes gives you the most flexibility.
With that being said, here are a couple of work arounds I can think of:
First, set up to recreated your scenario
Custom UIView
// Simple custom UIView with image view and selection UIView
fileprivate class CustomBorderView: UIView
{
private var isSelected = false
{
willSet
{
toggleBorder(newValue)
}
}
var imageView = UIImageView()
var selectionView = UIView()
init()
{
super.init(frame: CGRect.zero)
configureImageView()
configureSelectionView()
}
required init?(coder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews()
{
super.layoutSubviews()
}
private func configureImageView()
{
imageView.image = UIImage(named: "image-test")
imageView.contentMode = .scaleAspectFill
addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
imageView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
private func configureSelectionView()
{
selectionView.backgroundColor = .clear
selectionView.layer.borderWidth = 3
selectionView.layer.borderColor = UIColor.clear.cgColor
addSubview(selectionView)
selectionView.translatesAutoresizingMaskIntoConstraints = false
selectionView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
selectionView.topAnchor.constraint(equalTo: topAnchor).isActive = true
selectionView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
selectionView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
configureTapGestureRecognizer()
}
private func configureTapGestureRecognizer()
{
let tapGesture = UITapGestureRecognizer(target: self,
action: #selector(didTapSelectionView))
selectionView.addGestureRecognizer(tapGesture)
}
#objc
private func didTapSelectionView()
{
isSelected = !isSelected
}
private func toggleBorder(_ on: Bool)
{
if on
{
selectionView.layer.borderColor = UIColor(red: 28.0/255.0,
green: 244.0/255.0,
blue: 162.0/255.0,
alpha: 1.0).cgColor
return
}
selectionView.layer.borderColor = UIColor.clear.cgColor
}
}
Then in the view controller
class ClippingTestViewController: UIViewController
{
private let mainContainerView = UIView()
private let customView = CustomBorderView()
override func viewDidLoad()
{
super.viewDidLoad()
view.backgroundColor = .white
title = "Clipping view"
configureMainContainerView()
configureCustomBorderView()
mainContainerView.layer.cornerRadius = 50
mainContainerView.clipsToBounds = true
}
private func configureMainContainerView()
{
mainContainerView.backgroundColor = .white
view.addSubview(mainContainerView)
mainContainerView.translatesAutoresizingMaskIntoConstraints = false
mainContainerView.leadingAnchor.constraint(equalTo: view.leadingAnchor,
constant: 20).isActive = true
mainContainerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,
constant: 20).isActive = true
mainContainerView.trailingAnchor.constraint(equalTo: view.trailingAnchor,
constant: -20).isActive = true
mainContainerView.heightAnchor.constraint(equalToConstant: 300).isActive = true
view.layoutIfNeeded()
}
private func configureCustomBorderView()
{
mainContainerView.addSubview(customView)
customView.translatesAutoresizingMaskIntoConstraints = false
customView.leadingAnchor.constraint(equalTo: mainContainerView.leadingAnchor).isActive = true
customView.topAnchor.constraint(equalTo: mainContainerView.safeAreaLayoutGuide.topAnchor).isActive = true
customView.trailingAnchor.constraint(equalTo: mainContainerView.trailingAnchor).isActive = true
customView.bottomAnchor.constraint(equalTo: mainContainerView.bottomAnchor).isActive = true
view.layoutIfNeeded()
}
}
This gives me your current experience
Work Around 1. - Shrink subviews on selection
When the view is not selected, everything looks fine. When the view is selected, you could reduce the width and height of the custom subview with some animation while adding the border.
Work Around 2. - Manually clip desired subviews
You go through each subview in your container view and:
Apply the clipping to any subview you desire
Apply the corner radius to the views you clip
Leaving the container view unclipped and without a corner radius
To do that, I created a custom UIView subclass for the container view
class ClippingSubView: UIView
{
override var clipsToBounds: Bool
{
didSet
{
if clipsToBounds
{
clipsToBounds = false
clipImageViews(in: self)
layer.cornerRadius = 0
}
}
}
// Recursively go through all subviews
private func clipImageViews(in view: UIView)
{
for subview in view.subviews
{
// I am only checking image view, you could check which you want
if subview is UIImageView
{
print(layer.cornerRadius)
subview.layer.cornerRadius = layer.cornerRadius
subview.clipsToBounds = true
}
clipImageViews(in: subview)
}
}
}
Then make sure to adjust the following lines where you create your views:
let mainContainerView = ClippingSubView()
// Do this only after you have added all the subviews for this to work
mainContainerView.layer.cornerRadius = 50
mainContainerView.clipsToBounds = true
This gives me your desired output
This is a pretty common problem which may have multiple solutions. In the end though I always find it best to simply go one level higher:
ContainerView (Does not clip)
ContentView (Clips)
HighlightingView (Does not clip)
You would put all your current views on ContentView. Then introduce another view which represents your selection and put it on the same level as your ContentView.
In the end this will give you most flexibility. It can still get a bit more complicated when you add things like shadows. But again "more views" is usually the end solution.
You'll likely run into a lot of problems trying to get a subview's border to display outside its superView's clipping bounds.
One approach is to add an "Outline View" as a sibling of the "Clipping View":
When you select a clippingView's subview - and drag it around - set the frame of the outlineView to match the frame of that subview.
You'll want to set .isUserInteractionEnabled = false on the outlineView so it doesn't interfere with touches on the subviews.
We are currently working in an older codebase for our iOS application and are running into a weird bug where the UIScrollViews paging is not matching on the initialization but only once a user selects the button to change the view.
Expected Result:
The result we have:
Each ScrollView has three slides nested inside of them. We initialize the ScrollView like this:
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
private func commonInit() {
Bundle.main.loadNibNamed("DIScrollView", owner: self, options: nil)
contentView.frame = self.bounds
addSubview(contentView)
contentView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
contentView.layer.borderColor = UIColor.white.cgColor
contentView.layer.borderWidth = 2.0
scrollView.delegate = self
setUpScrollViewer()
}
You can see we call to set up the ScrollView and that is done like this:
public func setUpScrollViewer() {
let slides = self.createSlides()
let defaultIndex = 1
scrollView.Initialize(slides: slides, scrollToIndex: defaultIndex)
pageControl.numberOfPages = slides.count
pageControl.currentPage = defaultIndex
}
Now that all the content is available for each slide, we want to handle the content and we do so with a ScrollView extension:
extension UIScrollView {
//this function adds slides to the scrollview and constraints to the subviews (slides)
//to ensure the subviews are properly sized
func Initialize(slides:[UIView], scrollToIndex:Int) {
//Take second slide to base size from
let frameWidth = slides[1].frame.size.width
self.contentSize = CGSize(width: frameWidth * CGFloat(slides.count), height: 1)
for i in 0 ..< slides.count {
//turn off auto contstraints. We will be setting our own
slides[i].translatesAutoresizingMaskIntoConstraints = false
self.addSubview(slides[i])
//pin the slide to the scrollviewers edges
if i == slides.startIndex {
slides[i].leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
} else { //pin each subsequent slides leading edge to the previous slides trailing anchor
slides[i].leadingAnchor.constraint(equalTo: slides[i - 1].trailingAnchor).isActive = true
}
slides[i].topAnchor.constraint(equalTo: self.topAnchor).isActive = true
slides[i].widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
slides[i].heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
}
//the last slides trailing needs to be pinned to the scrollviewers trailing.
slides.last?.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
self.scrollRectToVisible(CGRect(x: frameWidth * CGFloat(scrollToIndex), y: 0, width: frameWidth, height: 1), animated: false)
}
}
I have tried manually setting contentOffset and nothing seems to be adjusting on the initialization. If the user selects the button it hides and then unhides it to display it properly with no logic adjusting this. Giving me the impression this issue is on the init.
Summary:
When the main view loads, the scrollView is showing me the first slide in the index when i need to be focused on the second slide. However if the user hides and then unhides the scrollView it works as intended.
How do i get the UIScrollView to actually load and initialize updating the scrollView to show the second slide and not initialize on the first slide?
Try explicitely running the scrollRectToVisible in the main thread using
DispatchQueue.main.async {
}
My guess is that all this code runs before the views are positioned by the layout system, and the first slide’s frame is the default 0 x 0 size. When the app returns to this view auto layout has figured out the size of this slide, so the calculation works.
Tap into the layout cycle to scroll to the right place after the layout. Maybe override viewDidLayoutSubviews() to check if it’s in the initial layout and then set the scroll position.
Use constraints for your contentView instead setting frame and autoresizingMask.
Call view.layoutIfNeeded() in the viewController before scrollRectToVisible or setContentOffset(I prefer the last)
I'm adding a custom titleView inside a navigation bar using navigationItem.titleView for both Master/Detail VC. On changing the orientation of the device to landscape, titleView under MasterViewController works fine, but for DetailViewController titleView disappears. On changing the orientation back to portrait titleView appears back for DetailViewController. I have also attached a link for source code and video.
Is this an intended behavior or am I making a mistake from my side or is it an issue from Apple's side ?
//Custom Title View:
class TitleView: UIView {
override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: 50, height: 20)
}
}
class DetailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Adding titleView for Master/Detail VC:
navigationItem.titleView = {
//Setting frame size here, did not make any difference
let view = TitleView(frame: .zero)
view.backgroundColor = .red
return view
}()
}
}
Full source code here: https://github.com/avitron01/SplitViewControllerIssue/tree/master/MathMonsters
Video highlighting the issue:
https://vimeo.com/336288580
I had the same issue. It seems an iOS bug. My workaround was to reassign the title view on every view layout. I used this piece of code in my DetailViewController:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let v = navigationItem.titleView {
navigationItem.titleView = nil
navigationItem.titleView = v
}
}
For those who stumble upon this, see also iOS 11 navigationItem.titleView Width Not Set. Basically, there's two suggested workarounds:
use a custom UIView that tells iOS to treat its intrinsicContentSize to be as big as possible with UIView.layoutFittingExpandedSize
use widthAnchor/heightAnchor constraints to set width and height of your view
I have two views
One is container of AVPlayerLayer like this
containerView.layer.addSublayer(playerLayer)
and containerView has own auto layout about superview
self.view.addSubview(containerView)
containerView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
containerView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
containerView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
containerView.heightAnchor.constraint(equalToConstant: 300).isActive = true
so i override viewDidLayoutSubviews()
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
playerLayer.frame = containerView.frame
}
and second view is custom playback control view on containerView
containerView.addSubview(playBackControlView)
playBackControlView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
playBackControlView.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
playBackControlView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
playBackControlView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
and there are several views like UIButton, UISlider etc
Here is my question
when i tapped one of buttons on playBackControlView which called enlargeScreenButton how can make my containerView, playBackControlView and AVPlayerLayer gonna be a full screen like landscape mode at once
I read this question already but only playerLayer changed, not whole view
(I will not device rotation)
I did many thing on Stackoverflow but they were fit on my case
if i transform some views are broken and if i change frame with UIScreen.main.bounds also it broke some views
I'd suggest you create a PlayerView subclass with custom layer view as such:
class PlayerView: UIView
override class var layerClass: AnyClass {
return AVPlayerLayer.self
}
}
This way you'll be able to manipulate the view without caring about the sublayer and it's animation. Then you'd be able to use the animations similar to ones from the answer you mentioned, but on the view. With all the subviews added using auto layout - you should be good to go and they should change accordingly when you animate using UIView.animate
I have a programmatically made view controller with subviews that are positioned using constraints. When I push this view controller into view using a navigation controller with the animation disabled...
let viewController = InventoryViewController()
navigationController?.pushViewController(viewController, animated: false)
...the view controller does not simply appear on screen, its subviews (the ones with constraints) expand outward and into view. Subviews that are not given constraints simply appear on screen as expected. So obviously, auto layout is animating itself into view. How do I disable this animation and just have the subviews appear on screen?
class InventoryViewController: UIViewController {
override func loadView() {
view = UIView()
view.frame = UIScreen.main.bounds
view.backgroundColor = UIColor.white
addButton()
}
func addButton() {
let button = UIButton()
button.backgroundColor = UIColor.black
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(button)
button.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true
button.topAnchor.constraint(equalTo: view.topAnchor, constant: 36).isActive = true
button.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -32).isActive = true
button.heightAnchor.constraint(equalToConstant: 48).isActive = true
}
#objc func buttonAction() {
//
}
}
Pushing the view controller is what causes its view to be loaded. You could try to force this to load and layout before the push:
let viewController = InventoryViewController()
viewController.view.layoutIfNeeded()
navigationController?.pushViewController(viewController, animated: false)
loadView() is not a good place to configure your subviews, it should be used only to put the views in your view hierarchy, probably that is why you view is animating.
Try to set your subviews on viewDidLoad() method.
Please look the discussion section in the official documentation: https://developer.apple.com/documentation/uikit/uiviewcontroller/1621454-loadview
Call your method from viewDidLayoutSubviews after super.viewDidLayoutSubviews. And animation will not be seen. As the reason behind this is using Autolayout, frame of your views are set when the autolayout engine starts its calculation.
This method is called when the autolayout engine has finished to calculate your views' frames
use
UIView.setAnimationsEnabled(false)
You use layoutIfNeeded() on the view they are added to, to force layout/redraw immediately.
Do this in viewDidLoad or try right after you have set the constraints.
or try:
layoutSubviews()
setNeedsLayout()
layoutSubviews()