I am trying to add a subview to view and define autolayout constraints, including aspect ratio. But aspect ratio that I see at runtime is not what I defined in constraints. What am I doing wrong? As you can see in code, background view height should be 0.5 of background view width, but that's not the case here in the screenshot. Here is my code:
class ViewController: UIViewController {
private var backgroundView:UIView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.orange
backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
backgroundView?.backgroundColor = UIColor.black.withAlphaComponent(1.0)
backgroundView?.layer.borderColor = UIColor.white.cgColor
backgroundView?.layer.borderWidth = 1.5
backgroundView?.layer.cornerRadius = 4
backgroundView?.clipsToBounds = true
backgroundView?.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(backgroundView!)
backgroundView?.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true
backgroundView?.heightAnchor.constraint(equalTo: backgroundView!.widthAnchor, multiplier: 0.5).isActive = true
backgroundView?.centerXAnchor.constraint(equalTo: view!.centerXAnchor, constant: 0).isActive = true
backgroundView?.topAnchor.constraint(equalTo: view!.topAnchor, constant: 4).isActive = true
}
}
Here is the screenshot:
"background view height should be 0.5 of background view width"
Your screenshot size is 1334 x 750
Your backgroundView - including the border - is 1334 x 667
1334 * 0.5 == 667
So, you are getting exactly what you are asking for.
Try to change height constraint to set:
backgroundView?.heightAnchor.constraint(equalTo: view!.heightAnchor, multiplier: 0.5).isActive = true
NB: You are getting the exact result which you are looking for. It has the height that's half of its width. There is nothing wrong with the screenshot.
Related
I have a Shuffle package added to my project (https://cocoapods.org/pods/Shuffle-iOS), the package works fine, but the problem is that even though I set cards width and height to my UIView, cards are out of UIView anyways, I tried changing the frame of my cards and set width and height to UIViews, but they are still out of UIView any solutions?
my UIView is mainView in code below
func card1(index: swipeCardData) -> SwipeCard {
let card = SwipeCard()
card.swipeDirections = [.left, .right, .up]
card.layer.cornerRadius = 12
card.layer.shadowOffset = CGSize.zero
card.layer.shadowOpacity = 1.0
card.layer.shadowRadius = 6.0
card.layer.masksToBounds = false
card.layer.borderWidth = 2
let view_bg = UIView(frame: CGRect(x: 16, y: 60, width: mainView.frame.size.width, height: mainView.frame.height)) // here is set cards width and frame to my UIView
card.content = view_bg
view_bg.layer.cornerRadius = 12
view_bg.clipsToBounds = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [self] in
let view_bg1 = UIView(frame: CGRect(x: 0, y: 0, width: view_bg.frame.size.width, height: view_bg.frame.size.height))
card.content?.addSubview(view_bg1)
let img_card_type = UIImageView(frame: CGRect.zero)
img_card_type.contentMode = .scaleAspectFit
img_card_type.translatesAutoresizingMaskIntoConstraints = false
img_card_type.isHidden = true
view_bg1.addSubview(img_card_type)
img_card_type.centerXAnchor.constraint(equalToSystemSpacingAfter: view_bg1.centerXAnchor, multiplier: 1).isActive = true
img_card_type.topAnchor.constraint(equalTo: view_bg1.topAnchor, constant: 0).isActive = true
img_card_type.widthAnchor.constraint(equalToConstant: 100).isActive = true
pictures for better understanding :
as you can see on the screenshot above the card content is out of mainView which is in the background(gray box)
the end result below
The reason is you are not providing height for image view and telling to expand according to aspect ratio of image. set a max height for image view. to better UX centre imageview in both axis and a fixed either height or width and a maximum for other width or height.
img_card_type.centerXAnchor.constraint(equalToSystemSpacingAfter: view_bg1.centerXAnchor, multiplier: 1).isActive = true
img_card_type.centerYAnchor.constraint(equalToSystemSpacingAfter: view_bg1.centerYAnchor, multiplier: 1).isActive = true
img_card_type.widthAnchor.constraint(equalToConstant: 100).isActive = true
img_card_type.heightAnchor.constraint(lessThanOrEqualToConstant: 100).isActive = true
I have an UIView that is defined below -
private let verticalSeparatorLine: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.alpha = 0.94
view.backgroundColor = .lightGray
return view
}()
This is how I add it to the viewcontroller's view.
override func viewDidLoad() {
super.viewDidLoad()
addTestView()
}
private func addTestView() {
view.addSubview(verticalSeparatorLine)
NSLayoutConstraint.activate([
verticalSeparatorLine.centerX.constraint(to: view.centerX),
verticalSeparatorLine.bottomAnchor.constraint(to: view.bottomAnchor),
verticalSeparatorLine.widthAnchor.constraint(0.3),
verticalSeparatorLine.heightAnchor.constraint(70)
])
}
If I add this verticalSeparatorLine to the ViewController's view in a larger device like iPhone X, the view lays out as expected. In smaller devices the view's width is zero. If I increase the width to say 2, it appears on both the devices.
Am I missing something?
Update:
If I replace with leadingAnchor, verticalSeparatorLine is visible with a width of 0.5.
verticalSeparatorLine.leadingAnchor.constraint(to: view.leadingAnchor, constant: 10),
It depends on the device's resolution, if UIScreen.main.scale == 2 means you set width 1 equals to 2 pixel's width, so 0.3(0.6pixel) can't be displayed, but in scale3 device, 0.33 just equals to 1 pixel.
I use the following setup:
The ViewControllers view holds a UIScrollView with Top, Leading, Trailing and Bottom constraints to match the VCs size
The ScrollView contains two subviews:
A UIView to define the content size of the scroll view. It has the same height as the ScrollView but twice its width. Thus only horizontal scrolling is possible.
A UILabel with some long text with a Height and Width constraint to set a fixed size and a Top and Leading constraint to the ScrollView to set a fixed position.
The width of the Label is changed when the ScrollView scrolls.
Problem: If the Label is set to use more than one line AND the ScrollViews contenOffset property is set manually the ScrollView stops scrolling.
ViewController View
+---------------------+
|+-------------------+|
||ScrollView ||
||+------------------||--------------------+
|||UIView to define || content size |
||| || |
||| || |
||| [MultiLine] || |
||| [ Label ] || |
||| || |
||+------------------||--------------------+
|+-------------------+|
+---------------------+
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
// Setting the ContentOffset will stop scrolling
//[self.scrollView setContentOffset:CGPointMake(0, 0)];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// Resize Label when scrolling
self.labelWidthConstraint.constant = MAX (50, 50 + self.scrollView.contentOffset.x);
}
Resizing the label using this code works fine if
the label is set use one line. In this case setting the setting the content offset does NOT do any harm. OR
the content offset is not changes (not even set to (0, 0)). In this case setting the label to multi line does NOT do any harm
Setting the content offset AND using multi line at the same time DOES NOT work. The scroll cannot be scrolled any more.
Why is this? Any idea what might cause this and how to solve it?
The issue appears to be that when the label constraints are changed it triggers viewDidLayoutSubviews which then sets the UIScrollView to not scroll since set contentOffset is then called over and over. You could overcome this if you are only wanting to set the UIScrollView to CGPoint.zero on the initial layout by using a bool as a flag. Apparently since UILabel needs a redraw on size changes it triggers viewDidLayoutSubviews. Here is an example in Swift.
import UIKit
class ViewController: UIViewController {
lazy var scrollView : UIScrollView = {
let sv = UIScrollView(frame: self.view.bounds)
sv.translatesAutoresizingMaskIntoConstraints = false
sv.delegate = self
return sv
}()
lazy var contentView : UIView = {
let v = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width * 4, height: self.view.bounds.height))
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
lazy var label : UILabel = {
let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 50))
lbl.numberOfLines = 0
lbl.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s"
lbl.minimumScaleFactor = 0.5
lbl.adjustsFontSizeToFitWidth = true
lbl.font = UIFont.systemFont(ofSize: 22)
lbl.translatesAutoresizingMaskIntoConstraints = false
return lbl
}()
var widthConstraint : NSLayoutConstraint?
var heightConstraint : NSLayoutConstraint?
var startingHeight : CGFloat = 0
var startingWidth : CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
//first scrollview
self.view.addSubview(scrollView)
pinToAllSides(target: scrollView)
//now content view
self.scrollView.addSubview(contentView)
contentView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 2).isActive = true
contentView.heightAnchor.constraint(equalTo: self.scrollView.heightAnchor, multiplier: 1).isActive = true
contentView.backgroundColor = .green
pinToAllSides(target: contentView)
scrollView.layoutIfNeeded()
//now the label
self.scrollView.addSubview(label)
label.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 20).isActive = true
label.topAnchor.constraint(equalTo: self.scrollView.topAnchor, constant: 60).isActive = true
label.backgroundColor = .red
widthConstraint = NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.view.bounds.width/2)
heightConstraint = NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 300)
if let wc = widthConstraint,
let hc = heightConstraint{
startingHeight = hc.constant
startingWidth = wc.constant
label.addConstraint(wc)
label.addConstraint(hc)
}
}
func pinToAllSides(target:UIView){
guard let superview = target.superview else{
return
}
target.leadingAnchor.constraint(equalTo: superview.leadingAnchor).isActive = true
target.trailingAnchor.constraint(equalTo: superview.trailingAnchor).isActive = true
target.topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
target.bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
}
var hasHappenedOnce : Bool = false
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if hasHappenedOnce == false{
hasHappenedOnce = true
self.scrollView.contentOffset = .zero
}
}
}
extension ViewController : UIScrollViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//hopefully it is laggy due to simulator but for the label i would ditch constraints myself
self.widthConstraint?.constant = max(startingWidth, self.scrollView.contentOffset.x * 1.1 + startingWidth)
let height = startingHeight - self.scrollView.contentOffset.x
self.heightConstraint?.constant = height
label.updateConstraints()
}
}
The problem is here:
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
// Setting the ContentOffset will stop scrolling
[self.scrollView setContentOffset:CGPointMake(0, 0)];
}
Changing self.labelWidthConstraint.constant when scrolling the scroll view triggers viewDidLayoutSubviews! So, as soon as you start scrolling, your code immediately resets .contentOffset to 0,0.
I don't know why you would want to be calling setContentOffset anyway, certainly not in viewDidLayoutSubviews.
Doing a quick test, after removing the viewDidLayoutSubviews code...
I called [self.scrollView setContentOffset:CGPointMake(0, 0)]; at the end of viewDidload (and also tried in viewDidAppear)... the scrolling (and constraint constant updating) continues to work fine.
I also added a button that calls [self.scrollView setContentOffset:CGPointMake(0, 0)]; when tapped... the scrolling (and constraint constant updating) continues to work fine.
I have a full screen scrollView, to which I add an imageView as subview. I want the imageView to be centered and scaled filling the scrollView's size (that is the screen size) at the beginning, but then to allow the user to scroll the image in both directions (vertical and horizontal) with equal offsets at left, right, top and bottom.
I mean: I've set the scroll view's contentSize to be CGSize(width: screenWidth + 200, height: screenHeight + 200), and if I run the app, I see that I am able to scroll those 200 pts of offset only to the right and to the bottom of the image. I'd like the image to be centered in the content size, and to be able to scroll it horizontally to both to the left and to the right with offset 100 pts each side (similar thing with top and bottom when scrolling vertically).
How could I achieve this?
Note: I'm setting all the UI in code, I'm not using storyboards nor xib files
You may find it easier / more intuitive to use constraints and auto-layout rather than screenWidth and screenHeight:
//
// CenteredScrollViewController.swift
// SW4Temp
//
// Created by Don Mag on 4/18/18.
//
import UIKit
class CenteredScrollViewController: UIViewController {
let theScrollView: UIScrollView = {
let v = UIScrollView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = UIColor.green
return v
}()
let theImageView: UIImageView = {
let v = UIImageView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = UIColor.blue
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
// add the scrollView to the main view
view.addSubview(theScrollView)
// add the imageView to the scrollView
theScrollView.addSubview(theImageView)
// pin the scrollView to all four sides
theScrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0.0).isActive = true
theScrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0).isActive = true
theScrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
theScrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0).isActive = true
// constrain the imageView's width and height to the scrollView's width and height
theImageView.widthAnchor.constraint(equalTo: theScrollView.widthAnchor, multiplier: 1.0).isActive = true
theImageView.heightAnchor.constraint(equalTo: theScrollView.heightAnchor, multiplier: 1.0).isActive = true
// set the imageView's top / bottom / leading / trailing anchors
// this *also* determines the scrollView's contentSize (scrollable area)
// with 100-pt padding on each side
theImageView.topAnchor.constraint(equalTo: theScrollView.topAnchor, constant: 100.0).isActive = true
theImageView.bottomAnchor.constraint(equalTo: theScrollView.bottomAnchor, constant: -100.0).isActive = true
theImageView.leadingAnchor.constraint(equalTo: theScrollView.leadingAnchor, constant: 100.0).isActive = true
theImageView.trailingAnchor.constraint(equalTo: theScrollView.trailingAnchor, constant: -100.0).isActive = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// set the scrollView's contentOffset (to center the imageView)
theScrollView.contentOffset = CGPoint(x: 100, y: 100)
}
}
You can move only down and right because your current content offset is 0,0 so top left - thus you can move down 200 and right 200.
What you want is to be scrolled 1/2 of vertical padding and 1/2 of horizontal padding, so in your case you would do scrollView.contentOffset = CGPoint(x: 100, y: 100)
Also for everything to work, UIImageView has to be same size as scrollView's contentSize, so bigger than screen size.
Given the comments what I think you want is the image to fill the screen and then user could scroll outside of bounds of the image, then you just need to make UIImageView's size be size of the screen its x and y coordinates to be same as contentOffset of the scrollView so (100, 100).
Here is the video of the sample app doing this:
https://dzwonsemrish7.cloudfront.net/items/2v361r2p0O2j1D3x3W10/Screen%20Recording%202018-04-19%20at%2002.32%20PM.mov
try this in
Swift 4.* or 5.*
let maxScale = self.imageScrollView.maximumZoomScale
let minScale = self.imageScrollView.minimumZoomScale
if let imageSize = imageView.image?.size{
let topOffset: CGFloat = (boundsSize.height - minScale * imageSize.height ) / 2
let leftOffset: CGFloat = (boundsSize.width - minScale * imageSize.width ) / 2
self.imageScrollView.contentInset = UIEdgeInsets(top: topOffset, left: leftOffset, bottom: 0, right: 0)
}
I have added a scrollview subview in one of my views, but am having trouble getting it's height to accurately fit the content that the scrollview is showing, which is text in the UILabel. The height needs to be dynamic (i.e. a factor of the text length), because I am instantiating this view for many different text lengths. Whenever I log label.frame.bounds I get (0,0) back. I have also tried sizeToFits() in a few places without much luck.
My goal is to get the scrollview to end when it reaches the last line of text. Also, I am using only programmatic constraints.
A condensed version of my code is the following:
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
let scrollView = UIScrollView()
let containerView = UIView()
let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
// This needs to change
scrollView.contentSize = CGSize(width: 375, height: 1000)
scrollView.addSubview(containerView)
view.addSubview(scrollView)
label.text = unknownAmountOfText()
label.backgroundColor = .gray
containerView.isUserInteractionEnabled = true
containerView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
containerView.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height)
}
}
Any help is appreciated.
SOLUTION found:
func heightForLabel(text: String, font: UIFont, lineHeight: CGFloat, width: CGFloat) -> CGFloat {
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.setLineHeight(lineHeight: lineHeight)
label.sizeToFit()
return label.frame.height
}
I found this solution online, that gives me what I need to set the appropriate content size for the scrollView height based on the label's height. Ideally, I'd be able to determine this without this function, but for now I'm satisfied.
The key to UIScrollView and its content size is setting your constraints so that the actual content defines the contentSize.
For a simple example: say you have a UIScrollView with width: 200 and height: 200. Now you put a UIView inside it, that has width: 100 and height: 400. The view should scroll up and down, but not left-right. You can constrain the view to 100x400, and then "pin" the top, bottom, left and right to the sides of the scroll view, and AutoLayout will "auto-magically" set the scrollview's contentSize.
When you add subviews that can change size - either explicitly (code, user interaction) or implicitly - if the constraints are set correctly those changes will also "auto-magically" adjust the scrollview's contentSize.
So... here is an example of what you are trying to do:
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
let scrollView = UIScrollView()
let label = UILabel()
let s1 = "1. This is the first line of text in the label. It has words and punctuation, but no embedded line-breaks, so what you see here is normal UILabel word-wrapping."
var counter = 1
override func viewDidLoad() {
super.viewDidLoad()
// turn off translatesAutoresizingMaskIntoConstraints, because we're going to set them
scrollView.translatesAutoresizingMaskIntoConstraints = false
label.translatesAutoresizingMaskIntoConstraints = false
// set background colors, just so we can see the bounding boxes
self.view.backgroundColor = UIColor(red: 1.0, green: 0.7, blue: 0.3, alpha: 1.0)
scrollView.backgroundColor = UIColor(red: 0.8, green: 0.8, blue: 1.0, alpha: 1.0)
label.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
// add the label to the scrollView, and the scrollView to the "main" view
scrollView.addSubview(label)
self.view.addSubview(scrollView)
// set top, left, right constraints on scrollView to
// "main" view + 8.0 padding on each side
scrollView.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor, constant: 8.0).isActive = true
scrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8.0).isActive = true
scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8.0).isActive = true
// set the height constraint on the scrollView to 0.5 * the main view height
scrollView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.5).isActive = true
// set top, left, right AND bottom constraints on label to
// scrollView + 8.0 padding on each side
label.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 8.0).isActive = true
label.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 8.0).isActive = true
label.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -8.0).isActive = true
label.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -8.0).isActive = true
// set the width of the label to the width of the scrollView (-16 for 8.0 padding on each side)
label.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -16.0).isActive = true
// configure label: Zero lines + Word Wrapping
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = UIFont.systemFont(ofSize: 17.0)
// set the text of the label
label.text = s1
// ok, we're done... but let's add a button to change the label text, so we
// can "see the magic" happening
let b = UIButton(type: UIButtonType.system)
b.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(b)
b.setTitle("Add a Line", for: .normal)
b.topAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 24.0).isActive = true
b.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
b.addTarget(self, action: #selector(self.btnTap(_:)), for: .touchUpInside)
}
func btnTap(_ sender: Any) {
if let t = label.text {
counter += 1
label.text = t + "\n\n\(counter). Another line"
}
}
}
give top,left,right and bottom constraint to label with containerView.
and
set label.numberOfLines = 0
also ensure that you have given top, left, right and bottom constraint to containerView. this will solve your issue
Set the auto layout constraints from the interface builder as shown in image .
enter image description here
I set the height of UIScrollView as 0.2 of the UIView
Then drag the UIlabel from MainStoryBoard to the view controller.
Add this two lines in viewdidload method.
draggedlabel.numberOfLines = 0
draggedlabel.lineBreakMode = NSLineBreakMode.byWordWrapping