Can't set size for UIImageView - swift

I have a UIImageView, I'm trying to give it a fixed size, but it won't work, the size of the UIImageView just won't change.
this is my UIImageView:
private let profileImg: UIImageView = {
let img = UIImageView(image: UIImage(named: "profileplaceholder"))
img.contentMode = .scaleAspectFill
img.layer.borderWidth = 1.0
img.layer.borderColor = UIColor.appPurple.cgColor
img.layer.cornerRadius = img.frame.width / 2
img.clipsToBounds = true
img.frame.size.width = 80
img.frame.size.height = 80
return img
}()
I added the image to a UIStackView like that:
private lazy var mStack: UIStackView = {
let stack = UIStackView(arrangedSubviews: [self.profileImg, self.nickname, self.unfollowBtn])
stack.translatesAutoresizingMaskIntoConstraints = false
stack.distribution = .fill
stack.axis = .horizontal
stack.spacing = 1.0
return stack
}()

StackView will resize it's elements. You should give it constraint for fixed size:
private let profileImg: UIImageView = {
...
img.translatesAutoresizingMaskIntoConstraints = false
img.heightAnchor.constraint(equalToConstant: 80).isActive = true
img.widthAnchor.constraint(equalToConstant: 80).isActive = true
...
}()

Related

stack programmatically, giving space for bottom

i am trying to place the image below the text i add
class SolicitudViewController: BaseViewController {
lazy var imagePrincipal : UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "diseƱo")
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
//imageView.heightAnchor.constraint(equalToConstant: 50).isActive = true
//imageView.bottomAnchor.constraint(equalToConstant: 100).isActive = true
return imageView
}()
lazy var stackView : UIStackView = {
let stack = UIStackView()
stack.axis = .vertical
stack.distribution = .fill
stack.translatesAutoresizingMaskIntoConstraints = false
stack.addArrangedSubview(imagePrincipal)
//stack.addArrangedSubview(lblsubTitulo)
//stack.addArrangedSubview(lineView)
stack.addArrangedSubview(imageEvaluando2)
stack.addArrangedSubview(imageEvaluando3)
return stack
}()
lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stackView)
return scrollView
}()
override func viewDidLoad() {
super.viewDidLoad()
setSubtitle(subtitle: "test View")
}
I have tried to use this: stack.setCustomSpacing(30, after: imagePrincipal) but it positions the image on top, I want the image to be below the text

Displaying property with Horizontal and Vertical Stack View in Swift

I am new to swift . I am following the programmatic approach to create the view . I created two stack view . One is horizontal and other one is vertical. Into horizontal stack view I want to display the label property and Vertical stack view I want to display the Image. I want to display the image on left side and label properties on right side.
Here is the code I used ..
import UIKit
class PeopleCell: UITableViewCell {
static let identifier = "PeopleCell"
private lazy var mainStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .leading
return stackView
}()
private lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.distribution = .fill
stackView.alignment = .center
return stackView
}()
private lazy var lastnameTitleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.textAlignment = .center
return label
}()
private lazy var firstnameTitleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.textAlignment = .center
return label
}()
private lazy var peopleImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
// imageView.backgroundColor = .blue
return imageView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUpUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureCell(firstName: String, lastName: String) {
firstnameTitleLabel.text = "Firstname :\(firstName)"
lastnameTitleLabel.text = "Lastname : \(lastName)"
}
func configureImageCell(row: Int, viewModel: ViewModel) {
peopleImageView.image = nil
viewModel
.downloadImage(row: row) { [weak self] data in
let image = UIImage(data: data)
self?.peopleImageView.image = image
}
}
private func setUpUI() {
stackView.addArrangedSubview(lastnameTitleLabel)
stackView.addArrangedSubview(firstnameTitleLabel)
mainStackView.addArrangedSubview(peopleImageView)
mainStackView.addArrangedSubview(stackView)
contentView.addSubview(mainStackView)
// constraints
let safeArea = contentView.safeAreaLayoutGuide
mainStackView.topAnchor.constraint(equalTo: safeArea.topAnchor).isActive = true
mainStackView.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor).isActive = true
mainStackView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor, constant: 10).isActive = true
mainStackView.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -10).isActive = true
peopleImageView.heightAnchor.constraint(equalToConstant: 140).isActive = true
peopleImageView.widthAnchor.constraint(equalToConstant: 140).isActive = true
stackView.leadingAnchor.constraint(equalTo: mainStackView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: mainStackView.trailingAnchor).isActive = true
}
}
Here is the screenshot ..
Here is the expected result.
The main problem is that you have your .axis properties reversed.
You want your mainStackView.axis to be .horizontal and your stackView.axis to be .vertical.
Also, these two lines are not needed (and cause problems):
// don't do this
//stackView.leadingAnchor.constraint(equalTo: mainStackView.leadingAnchor).isActive = true
//stackView.trailingAnchor.constraint(equalTo: mainStackView.trailingAnchor).isActive = true
As a side note, instead of:
let safeArea = contentView.safeAreaLayoutGuide
you may want to use:
let safeArea = contentView.layoutMarginsGuide
which gives you the default cell margins.
Edit
// this is the "main" stack view with
// the image on the left
// the labels on the right
// so it needs to be HORIZONTAL
private lazy var mainStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
//stackView.axis = .vertical
stackView.axis = .horizontal
stackView.distribution = .fill
return stackView
}()
// this is the "labels" stack view with
// two (or more) labels from top down
// so it needs to be VERTICAL
private lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
//stackView.axis = .horizontal
stackView.axis = .vertical
stackView.distribution = .fill
return stackView
}()

Can't figure out why my stackviews are not arranging vertically

I have done this many times but this time for some reason won't work the way it usually does. Am I doing something wrong here? I am just trying to get two views into my UIstackView and distribute them vertically. It seems to keep overlapping and going all over the place. At one point it was only even showing one view.
My viewdidload():
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
view.addSubview(headerView)
view.addSubview(contentView)
contentView.addSubview(contentStack)
headerView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.30).isActive = true
headerView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
headerView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
headerView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
contentView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.70).isActive = true
contentView.widthAnchor.constraint(equalTo: self.view.widthAnchor,multiplier: 0.90).isActive = true
contentView.topAnchor.constraint(equalTo: headerView.bottomAnchor,constant: 20).isActive = true
contentView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
}
My Views and Labels:
fileprivate lazy var headerView : UIView = {
var view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .black
return view
}()
fileprivate lazy var contentView : UIView = {
var view = UIView()
view.backgroundColor = .lightGray
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
fileprivate lazy var contentStack : UIStackView = {
var stack = UIStackView(arrangedSubviews: [EarningsView,ListingsView,])
stack.translatesAutoresizingMaskIntoConstraints = true
stack.distribution = .fillEqually
stack.alignment = .fill
stack.axis = .vertical
// stack.spacing = 5
return stack
}()
fileprivate lazy var EarningsView : UIView = {
let EarningsView = UIView()
EarningsView.translatesAutoresizingMaskIntoConstraints = false
EarningsView.backgroundColor = .blue
EarningsView.addSubview(EarningsLabel)
EarningsView.addViewBorder(borderColor: UIColor.black.cgColor, borderWith: 0.5, borderCornerRadius: 0.0)
return EarningsView
}()
fileprivate lazy var EarningsLabel : UILabel = {
let EarningsLabel = UILabel()
EarningsLabel.translatesAutoresizingMaskIntoConstraints = false
let earningsText = NSAttributedString(string: "My Earnings", attributes: self.stringAttrib)
EarningsLabel.attributedText = earningsText
EarningsLabel.textColor = .black
EarningsLabel.backgroundColor = .white
EarningsLabel.textAlignment = .center
return EarningsLabel
}()
fileprivate lazy var ListingsView : UIView = {
let ListingsView = UIView()
ListingsView.translatesAutoresizingMaskIntoConstraints = false
ListingsView.addSubview(ListingLabel)
ListingsView.addViewBorder(borderColor: UIColor.black.cgColor, borderWith: 0.5, borderCornerRadius: 0.0)
ListingsView.backgroundColor = .red
return ListingsView
}()
fileprivate lazy var ListingLabel : UILabel = {
let ListingLabel = UILabel()
ListingLabel.translatesAutoresizingMaskIntoConstraints = false
let listingText = NSAttributedString(string: "My Listing", attributes: self.stringAttrib)
ListingLabel.attributedText = listingText
return ListingLabel
}()
This is driving me crazy because I have done it so many times before and now I have spent atleast 6 hours on this little part trying to figure it out. Of course I could just create a whole new viewcontroller but I just want to figure this out.
EarningsView, EarningsLabel, ListingsView, ListingLabel have
translatesAutoresizingMaskIntoConstraints = false
But they have no constraints added to replace the Autoresizing constraints, so they just act goofy and go up to the top left. I've seen stuff like this before. On my stuff. Either autosize or put in constraints.

Images not being rounded in UIStackView

I'm trying to round several images and add them in a stack view, for some reason it's not working. Basically, I have an array with all UIImage names and assign them to a UIImageView. When I try to make a circle out of the image, it's not working :
var navStackView : UIStackView = {
let stack = UIStackView()
stack.axis = .horizontal
stack.alignment = .center
stack.distribution = .fillEqually
// stack.spacing = -10
stack.translatesAutoresizingMaskIntoConstraints = false
return stack
}()
var images = ["1", "2", "3", "4"]
override func viewDidLoad() {
super.viewDidLoad()
let navController = navigationController!
navController.navigationBar.addSubview(navStackView)
// x, y, w, h
navStackView.leadingAnchor.constraint(equalTo: navController.navigationBar.leadingAnchor).isActive = true
navStackView.trailingAnchor.constraint(equalTo: navController.navigationBar.trailingAnchor).isActive = true
navStackView.topAnchor.constraint(equalTo: navController.navigationBar.topAnchor).isActive = true
navStackView.bottomAnchor.constraint(equalTo: navController.navigationBar.bottomAnchor).isActive = true
for image in images {
let imageView = UIImageView()
imageView.image = UIImage(named: image)
imageView.layer.cornerRadius = imageView.frame.height / 2
imageView.clipsToBounds = true
imageView.layer.masksToBounds = false
imageView.contentMode = .scaleAspectFit
// imageView.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
navStackView.addArrangedSubview(imageView)
navStackView.layoutIfNeeded()
}
navigationItem.titleView = navStackView
}
You can try
var once = true
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if once {
navStackView.subviews.forEach { $0.layer.cornerRadius = $0.frame.height / 2 }
once = false
}
}

How do I dynamically adjust the height of a UIView when a member stack view is no longer shown?

I am super new iOS development and StackViews in general and need help calculating dynamic height in instances where a stack view will not be shown. There are cases where certain elements will not be shown depending on what I get back from the server.
However, when I call removeArrangedSubview the element is removed but the height isn't adjusted dynamically. How can I fix this?
I would like to avoid the Interface Builder all together and just do this programmatically. I have been using layout anchors for constraints.
Here's my code. You can put in a playground to see it.
//: Playground - noun: a place where people can play
import UIKit
import Foundation
let view = UIView(frame: CGRect(x: 0, y: 0, width: 800, height: 140))
let firstStackView = UIStackView(frame: CGRectZero)
//firstStackView.heightAnchor.constraintGreaterThanOrEqualToConstant(40).active = true
firstStackView.axis = .Vertical
firstStackView.alignment = .Fill
firstStackView.distribution = .EqualSpacing
let titleStackView = UIStackView(frame: CGRectZero)
titleStackView.axis = .Horizontal
titleStackView.alignment = .Fill
titleStackView.distribution = .Fill
titleStackView.spacing = 3
firstStackView.addArrangedSubview(titleStackView)
let productStackView = UIStackView(frame: .zero)
productStackView.axis = .Horizontal
productStackView.alignment = .Leading
productStackView.distribution = .Fill
productStackView.spacing = 3
firstStackView.addArrangedSubview(productStackView)
//firstStackView.removeArrangedSubview(productStackView)
let secondStackView = UIStackView(frame: CGRectZero)
//secondStackView.heightAnchor.constraintEqualToConstant(30).active = true
secondStackView.axis = .Horizontal
secondStackView.distribution = .EqualSpacing
let title = UILabel(frame: CGRectZero)
title.text = "test1"
title.textColor = .blackColor()
//labelOne.backgroundColor = .blueColor()
let size = title.sizeThatFits(CGSizeZero)
print("\(size)")
title.widthAnchor.constraintEqualToConstant(size.width).active = true
//labelOne.heightAnchor.constraintEqualToConstant(30).active = true
titleStackView.addArrangedSubview(title)
let assigneeLabel = UILabel(frame: CGRectZero)
assigneeLabel.text = "test2"
assigneeLabel.textColor = .blackColor()
//labelTest.backgroundColor = .redColor()
assigneeLabel.textAlignment = .Left
//labelTest.heightAnchor.constraintEqualToConstant(30).active = true
titleStackView.addArrangedSubview(assigneeLabel)
let actions = UIButton(type: .Custom)
//buttonOne.backgroundColor = .redColor()
actions.setTitle("some button", forState: .Normal)
actions.setTitleColor(.blackColor(), forState: .Normal)
titleStackView.addArrangedSubview(actions)
let productOne = UILabel(frame: CGRectZero)
productOne.text = "something1"
productOne.numberOfLines = 0
let productLabelSize = productOne.sizeThatFits(CGSizeZero)
productOne.widthAnchor.constraintEqualToConstant(productLabelSize.width).active = true
productOne.textColor = .blackColor()
//labelTwo.backgroundColor = .blueColor()
productStackView.removeArrangedSubview(productOne)
//productStackView.addArrangedSubview(productOne)
let productTwo = UILabel(frame: CGRectZero)
productTwo.text = "something2"
productTwo.numberOfLines = 0
//productTwo.heightAnchor.constraintEqualToConstant(30).active = true
productTwo.textColor = .blackColor()
//labelTwo.backgroundColor = .blueColor()
productStackView.removeArrangedSubview(productTwo)
//productStackView.addArrangedSubview(productTwo)
let labelThree = UILabel(frame: CGRectZero)
labelThree.text = "sometime"
//labelThree.heightAnchor.constraintEqualToConstant(30).active = true
labelThree.textColor = .blackColor()
//labelThree.backgroundColor = .blueColor()
firstStackView.addArrangedSubview(labelThree)
let descriptionView = UILabel(frame: CGRectZero)
descriptionView.text = "some description about something"
descriptionView.textColor = .blackColor()
//descriptionView.backgroundColor = .redColor()
secondStackView.addArrangedSubview(descriptionView)
let tagsView = UILabel(frame: CGRectZero)
tagsView.text = "some more things"
tagsView.textColor = .blackColor()
secondStackView.addArrangedSubview(tagsView)
secondStackView.trailingAnchor.constraintEqualToAnchor(tagsView.trailingAnchor).active = true
let stackView = UIStackView(arrangedSubviews: [firstStackView, secondStackView])
stackView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
stackView.layoutMarginsRelativeArrangement = true
stackView.axis = .Vertical
stackView.frame = view.bounds
stackView.distribution = .FillProportionally
view.addSubview(stackView)
Before element is removed:
After element is removed:
I would like that gap to be gone and the height adjusted dynamically.
You can add a constraint for the height of the view if you are using auto layout.
So like for initial setup, you could do something like:
class YourClass : UIViewController() {
var heightConstraint = NSLayoutConstraint()
func someMethod () {
// load your View
// get the height of view.
heightConstraint = yourView.heightAnchor.constraintEqualToConstant(height)
self.view.addConstraint(heightConstraint)
}
func deleteMemberStackView() {
/// After deleting the member, get the new height of the view and do this
self.view.removeConstraint(heightConstraint)
heightConstraint = yourView.heightAnchor.constraintEqualToConstant(height)
self.view.addConstraint(heightConstraint)
UIView.animateViewDuration(0.3, completion: {
self.view.layoutIfNeeded()
})
}
}