Unable to Anchor UIImageVIew in UICollectionViewCell (programmatically) - ios

Working on specing out a view in Playground and can't seem to figure out why UIIMageView is being placed in the center of a UICollectionViewCell.
Relevant Code:
class BookCell: UICollectionViewCell {
static let identifier = "bookCell"
override init(frame: CGRect) {
super.init(frame: .zero)
self.layer.cornerRadius = 12
self.backgroundColor = .brown
addAllSubviews()
addAllConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
lazy var cover: UIImageView = {
let imageview = UIImageView()
imageview.translatesAutoresizingMaskIntoConstraints = false
var largeImage = UIImage(named: "medium.jpg")
imageview.image = largeImage
imageview.contentMode = .scaleAspectFit
//imageview.contentMode = .scaleToFill
return imageview
}()
func coverConstraints(){
NSLayoutConstraint.activate([
cover.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0),
/**widthConstraint*/
NSLayoutConstraint(item: cover,
attribute: .width,
relatedBy: .equal,
toItem: self,
attribute: .width,
multiplier: 1.0, constant: 0.0),
/**heightConstraint*/
NSLayoutConstraint(item: cover,
attribute: .height,
relatedBy: .equal,
toItem: self,
attribute: .height,
multiplier: 0.75, constant: 0.0)
])
}
let wordLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "test"
return label
}()
func wordLabelConstraints() {
NSLayoutConstraint.activate([
wordLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
wordLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
wordLabel.topAnchor.constraint(equalTo: cover.bottomAnchor, constant: 2)
])
}
// MARK: - Add Subviews
func addAllSubviews() {
self.addSubview(cover)
self.addSubview(wordLabel)
}
// MARK: - SubViews Constraints
func addAllConstraints() {
coverConstraints()
wordLabelConstraints()
}
}
BookCell is then used in a UICollectionViewController like so:
class ViewController: UIViewController {
fileprivate let collectionView: UICollectionView = {
let layout = ColumnFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = .blue
cv.translatesAutoresizingMaskIntoConstraints = false
return cv
}()
var data: [Int] = Array(0..<10)
override func loadView() {
super.loadView()
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.topAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16)
])
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.collectionView.register(BookCell.self, forCellWithReuseIdentifier: BookCell.identifier)
self.collectionView.alwaysBounceVertical = true
self.collectionView.backgroundColor = .yellow
}
}
Result:
I noticed that using scaleToFill instead of scaleAspectFit results in image covering the entire width of the cell. The result (see image below) fits what I am aiming for but ... see question below
Question:
Is using scaleToFill the only way to pin an image to the edges (leading and trailing) of UICollectionViewCell. If so, why is this?
I also tried adding the UIImageView to a UIStackView and I believe I got the same results.
Please note that I am not interested in doing this via Storyboard.
Thank you for providing feedback

There is one more option: .scaleAspectFill but may be cropped your image's content.
The option to scale the content to fill the size of the view.
Some portion of the content may be clipped to fill the view’s bounds.
Think about getting the image size ratio (width/height), you having a fixed width based on superview, and height will be based on the image Ratio.

Related

Self sizing cell with multiple Stack Views

I've looked all over the forum and attempted all the solutions and thus far nothing has worked. I noticed my UIImageView was overlaying multiple cells, meaning the celll did not automatically adjust its height. Here is the constraint i found in the console it complained about.
"<NSLayoutConstraint:0x600001970f50 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7f86a4813dd0.height == 44 (active)>"
In my tableViewController I have the follow
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 300
Here is my entire cell that should self size.
import UIKit
class UserConnectionCell: UITableViewCell {
fileprivate let leftImageView: UIImageView = {
let uiImageView = UIImageView()
uiImageView.translatesAutoresizingMaskIntoConstraints = false
return uiImageView
}()
fileprivate let leftLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
fileprivate let middleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.font = UIFont(name: "Ariel", size: 10)
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
fileprivate let rightImageView: UIImageView = {
let uiImageView = UIImageView()
uiImageView.translatesAutoresizingMaskIntoConstraints = false
return uiImageView
}()
fileprivate let rightLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
fileprivate let stackViewLeft: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
fileprivate let stackViewRight: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
fileprivate let stackViewMain: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.spacing = 0
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
//
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier:reuseIdentifier)
stackViewLeft.addArrangedSubview(leftImageView)
stackViewLeft.addArrangedSubview(leftLabel)
stackViewRight.addArrangedSubview(rightImageView)
stackViewRight.addArrangedSubview(rightLabel)
stackViewMain.addArrangedSubview(stackViewLeft)
stackViewMain.addArrangedSubview(middleLabel)
stackViewMain.addArrangedSubview(stackViewRight)
contentView.addSubview(stackViewMain)
}
// called when trying to layout subviews.
override func layoutSubviews() {
super.layoutSubviews()
stackViewLeft.addConstraint(NSLayoutConstraint(item: leftImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 100))
stackViewLeft.addConstraint(NSLayoutConstraint(item: leftImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 100))
stackViewRight.addConstraint(NSLayoutConstraint(item: rightImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 100))
stackViewRight.addConstraint(NSLayoutConstraint(item: rightImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 100))
NSLayoutConstraint.activate(
[stackViewMain.topAnchor.constraint(equalTo: contentView.topAnchor,constant: 0),
stackViewMain.leadingAnchor.constraint(equalTo: contentView.leadingAnchor,constant: 0),
stackViewMain.trailingAnchor.constraint(equalTo: contentView.trailingAnchor,constant: 0),
stackViewMain.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var viewModel : UserConnectionViewModel? {
didSet {
// move this to the view model
if let profileUrl = viewModel?.leftImageUrl {
leftImageView.loadImageFromURL(url: profileUrl)
} else {
leftImageView.image = UIImage(named: "defaultprofile")
}
if let profileUrl = viewModel?.rightImageUrl {
rightImageView.loadImageFromURL(url: profileUrl)
} else {
rightImageView.image = UIImage(named: "defaultprofile")
}
leftLabel.text = viewModel?.leftLabel
middleLabel.text = viewModel?.middleLabel
rightLabel.text = viewModel?.rightlabel
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.autoresizingMask = .flexibleHeight
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Any ideas for why the cell is not self sizing?
First, a cell's contentView is a "special" view with properties integral to the table view's operation.
So, do not do this:
self.contentView.autoresizingMask = .flexibleHeight
Second, layoutSubviews() can be (and usually is) called multiple times during the lifecycle of a cell / view. Your constraint setup should be done in init:
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier:reuseIdentifier)
stackViewLeft.addArrangedSubview(leftImageView)
stackViewLeft.addArrangedSubview(leftLabel)
stackViewRight.addArrangedSubview(rightImageView)
stackViewRight.addArrangedSubview(rightLabel)
stackViewMain.addArrangedSubview(stackViewLeft)
stackViewMain.addArrangedSubview(middleLabel)
stackViewMain.addArrangedSubview(stackViewRight)
contentView.addSubview(stackViewMain)
NSLayoutConstraint.activate([
// constrain main stack view to all 4 sides of contentView
stackViewMain.topAnchor.constraint(equalTo: contentView.topAnchor,constant: 0),
stackViewMain.leadingAnchor.constraint(equalTo: contentView.leadingAnchor,constant: 0),
stackViewMain.trailingAnchor.constraint(equalTo: contentView.trailingAnchor,constant: 0),
stackViewMain.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0),
// constrain left image view Width: 100-pts,
// Height equal to Width (1:1 ratio)
leftImageView.widthAnchor.constraint(equalToConstant: 100.0),
leftImageView.heightAnchor.constraint(equalTo: leftImageView.widthAnchor),
// constrain right image view Width: 100-pts,
// Height equal to Width (1:1 ratio)
rightImageView.widthAnchor.constraint(equalToConstant: 100.0),
rightImageView.heightAnchor.constraint(equalTo: rightImageView.widthAnchor),
])
}
So... replace your init with the above code and completely remove both your awakeFromNib() and layoutSubviews() funcs.
You should get this:

Preventing Auto Layout from stretching custom view

I've created a custom view in swift & am trying to get it to display appropriately. It is essentially a material card, with the ability to expand the view by pressing the more button. My issue comes in when specifying the bottom constraint. It is required, but setting it stretches my custom view.
I have implemented this already in android & I guess I'm trying to find the analog to android:height='wrap_content'. I've tried setting the aspect ratio constraint, which works to keep my view at the proper size, but prevents the custom view from expanding when its subviews change. Additionally I've tried using the lessThanOrEqualTo constraint, but that is too ambiguous to satisfy the bottom constraint.
This is what my UIExpandableCard view looks like:
import Foundation
import MaterialComponents
#IBDesignable
public class UIExpandableCard: UIView {
// attributes
#IBInspectable var overlineText: String? {
didSet {
overlineLabel.text = overlineText?.uppercased()
}
}
#IBInspectable var headlineText: String? {
didSet {
headlineLabel.text = headlineText
}
}
#IBInspectable var bodyText: String? {
didSet {
bodyLabel.text = bodyText
}
}
#IBInspectable var logoImage: UIImage? {
didSet {
logoImageView.image = logoImage
}
}
var cardView: MDCCard!
var overlineLabel: UILabel!
var headlineLabel: UILabel!
var bodyLabel: UILabel!
var moreButton: UIButton!
var logoImageView: UIImageView!
var isCardExpanded = false
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
self.translatesAutoresizingMaskIntoConstraints = false
setupViews()
setupConstraints()
}
private func setupViews() {
self.clipsToBounds = true
cardView = MDCCard(frame: CGRect.zero)
cardView.translatesAutoresizingMaskIntoConstraints = false
cardView.isInteractable = false
self.addSubview(cardView)
overlineLabel = UILabel(frame: CGRect.zero)
overlineLabel.translatesAutoresizingMaskIntoConstraints = false
overlineLabel.font = UIFont.preferredFont(forTextStyle: .footnote)
overlineLabel.text = overlineText?.uppercased()
self.addSubview(overlineLabel)
headlineLabel = UILabel(frame: CGRect.zero)
headlineLabel.translatesAutoresizingMaskIntoConstraints = false
headlineLabel.font = UIFont.preferredFont(forTextStyle: .title1)
headlineLabel.text = headlineText
self.addSubview(headlineLabel)
bodyLabel = UILabel(frame: CGRect.zero)
bodyLabel.translatesAutoresizingMaskIntoConstraints = false
bodyLabel.font = UIFont.preferredFont(forTextStyle: .body)
bodyLabel.numberOfLines = 1
bodyLabel.text = bodyText
self.addSubview(bodyLabel)
logoImageView = UIImageView(image: logoImage)
logoImageView.translatesAutoresizingMaskIntoConstraints = false
logoImageView.contentMode = .scaleAspectFit
self.addSubview(logoImageView)
moreButton = UIButton(type: .roundedRect)
moreButton.isUserInteractionEnabled = true
moreButton.translatesAutoresizingMaskIntoConstraints = false
moreButton.setTitle("More", for: .normal)
moreButton.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
self.addSubview(moreButton)
}
#objc func buttonClicked(_ sender: UIButton) {
if !isCardExpanded {
moreButton.setTitle("Less", for: .normal)
bodyLabel.numberOfLines = 0
} else {
moreButton.setTitle("More", for: .normal)
bodyLabel.numberOfLines = 1
}
isCardExpanded = !isCardExpanded
}
private func setupConstraints() {
NSLayoutConstraint.activate([
cardView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8),
cardView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8),
cardView.topAnchor.constraint(equalTo: self.topAnchor, constant: 8),
cardView.bottomAnchor.constraint(lessThanOrEqualTo: self.bottomAnchor, constant: -8),
overlineLabel.leadingAnchor.constraint(equalTo: cardView.leadingAnchor, constant: 16),
overlineLabel.topAnchor.constraint(equalTo: cardView.topAnchor, constant: 16),
headlineLabel.leadingAnchor.constraint(equalTo: cardView.leadingAnchor, constant: 16),
headlineLabel.topAnchor.constraint(equalTo: overlineLabel.bottomAnchor, constant: 8),
NSLayoutConstraint(item: logoImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 48),
NSLayoutConstraint(item: logoImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 48),
logoImageView.trailingAnchor.constraint(equalTo: cardView.trailingAnchor, constant: -16),
logoImageView.topAnchor.constraint(equalTo: cardView.topAnchor, constant: 16),
bodyLabel.leadingAnchor.constraint(equalTo: cardView.leadingAnchor, constant: 16),
bodyLabel.topAnchor.constraint(equalTo: logoImageView.bottomAnchor, constant: 16),
bodyLabel.trailingAnchor.constraint(equalTo: cardView.trailingAnchor, constant: -8),
moreButton.topAnchor.constraint(greaterThanOrEqualTo: bodyLabel.bottomAnchor, constant: 8),
moreButton.leadingAnchor.constraint(equalTo: cardView.leadingAnchor, constant: 16),
moreButton.bottomAnchor.constraint(equalTo: cardView.bottomAnchor, constant: -8)
])
}
}
Basically I want something like the left. However, I'm getting the right, where one of the views (in blue) is being stretched to fill the constraint.
left right
I'm relatively new to iOS, but have experience with android, so any explanations relating to that would be extra helpful.
Thanks.
So I found a solution that appears to do what I need. I'm still trying to wrap my head around what I was actually trying to achieve. Basically what I wanted was my view height to be defined by its subviews & their constraints, rather than having to specify it in a constraint. At the same time I needed to satisfy the height constraint in my interface.
My solution was as follows: add a low priority height constraint of 0 to the the card view in my interface. This satisfies the requirement for a height in the scene, while also allowing my view to expand & contract without being stretched.
... a low priority constraint of height zero for the view as a whole. The low priority constraint will try to shrink the assembly, while the other constraints stop it from shrinking so far that it clips its subviews.
I found this solution on another stack overflow question.
Following Joshua's answer, with this I prevented a custom view from stretching:
let width = widthAnchor.constraint(equalToConstant: 0)
width.priority = .defaultLow
width.isActive = true
You can't do that with lessThanOrEqualTo.Although i can't fully understand you're question but hope this approach help.
first of all define a flow constraint like:
var heightConstraint: NSLayoutConstraint?
and replace it with bottom constraint in setupConstraint:
private func setupConstraints() {
heightConstraint = cardView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([
cardView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8),
cardView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8),
cardView.topAnchor.constraint(equalTo: self.topAnchor, constant: 8),
heightConstraint,
overlineLabel.leadingAnchor.constraint(equalTo: cardView.leadingAnchor, constant: 16),
overlineLabel.topAnchor.constraint(equalTo: cardView.topAnchor, constant: 16),
.
.
.
and finally when press the button:
private func expandViewWithAnimation(_ isExpand: Bool) {
UIView.animate(withDuration: 0.8) {
self.heightConstraint?.constant = isExpand ? 80:0
self.layoutIfNeeded()
}
}
#objc func buttonClicked(_ sender: UIButton) {
if !isCardExpanded {
moreButton.setTitle("Less", for: .normal)
bodyLabel.numberOfLines = 0
} else {
moreButton.setTitle("More", for: .normal)
bodyLabel.numberOfLines = 1
}
expandViewWithAnimation(isCardExpanded)
isCardExpanded = !isCardExpanded
}
i can't comment on your post because don't have enough reputation :)

row height is not automatically updated

EDITED:
This is my custom cell class. It has a TextField and a TextView. Whatever I do I can't get the row height updated automatically. I know I can do it manually using heightForRowAt but I don't want to do that.
class customCell: UITableViewCell, UITextViewDelegate{
var didSetupConstraints = false
var titleField : UITextField = {
var textField = UITextField()
textField.placeholder = " Subject (optional)"
textField.backgroundColor = UIColor.lightGray
textField.translatesAutoresizingMaskIntoConstraints = false
textField.layer.cornerRadius = 3
textField.clipsToBounds = true
return textField
}()
var messageView : UITextView = {
var textView = UITextView()
textView.text = "Add your email here"
textView.translatesAutoresizingMaskIntoConstraints = false
textView.backgroundColor = UIColor.red
return UITextView()
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(titleField)
self.contentView.addSubview(messageView)
messageView.delegate = self
addConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addConstraints(){
contentView.addConstraints([titleField.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 23),titleField.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -18),titleField.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 18) ])
titleField.addConstraint(NSLayoutConstraint(item: titleField, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50))
contentView.addConstraints([messageView.topAnchor.constraint(equalTo: titleField.bottomAnchor, constant: 11),messageView.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -18),messageView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 18), messageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5)])
messageView.addConstraint(NSLayoutConstraint(item: messageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100))
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.setNeedsLayout()
contentView.layoutIfNeeded()
}
override func updateConstraints() {
if !didSetupConstraints {
addConstraints()
didSetupConstraints = true
}
super.updateConstraints()
}
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.textColor == UIColor.lightGray {
textView.text = nil
textView.textColor = UIColor.black
}
}
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Add your email here"
textView.textColor = UIColor.lightGray
}
}
}
I have already seen this question and from what I have understood the things I need to do are:
Add tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension which I have done in tableViewController
Add a bottom and top constraint: I have added a topAnchor to my TextField + a constraint between my TextField and TextView + a constraint between my TextView's bottomAnchor and the contentView bottomAnchor
I have added my constraints code into my updateConstraints() method.
Not sure if I need to do anything else, but I've done all three but it still doesn't work. I'm guessing that maybe my bottom/top constraints are not set up correctly. The current result that I get is (The textView isn't visible at all :(( )
yet what I expect to get is:
EDIT 2
See image:
After all the fixes, the only problem I have now is that the empty cells don't have the default size of 44, is it that the tableView is trying to be smart and adjusts the row height based on the last cell height?
A few things:
updateConstraints can be called multiple times by the system, so use a flag to only add your constraints the first time.
messageView.topAnchor.constraint(equalTo: titleField.topAnchor, constant: 11) should be messageView.topAnchor.constraint(equalTo: titleField.bottomAnchor, constant: 11)
Try giving your messageView a height.
As #Honey pointed out, textView was not returned in the initialization of messageView.
About empty cell heights, if you don't want empty cells at all, just do tableView.tableFooterView = UIView() to get rid of them. It's probably the table view being smart about cell heights, like you said.

iOS adding constraints programmatically in Swift

So, I'm done using the IB in Xcode and want to write all UI in Swift.
So what I've done is:
Created a new UIView to contain the elements i want to write - lets call it "TestView"
I've added TestView to a VC as a sub view.
In the TestView class I've added the elements like this:
class TestView: UIView {
var someLabel:UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
self.someLabel = UILabel(frame: CGRect(x: self.frame.midX, y: oneSixthHeight, width: 100, height: 22))
self.someLabel.text = "test"
var constraints:[NSLayoutConstraint] = []
self.someLabel.translatesAutoresizingMaskIntoConstraints = false
let rightsideAnchor:NSLayoutConstraint = NSLayoutConstraint(item: self.someLabel, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 1)
constraints.append(rightsideAnchor)
NSLayoutConstraint.activateConstraints(constraints)
}
}
With this I expect the UILabel to be anchored to the right side of the view.
However, I do get this error:
Terminating app due to uncaught exception 'NSGenericException',
reason: 'Unable to activate constraint with items > and > because they have no common ancestor.
Does the constraint reference items in different view hierarchies? That's illegal.'
What am I doing wrong?
You should add constraints only after view is added to the view hierarchy. From your code it is clear that you have not added the UILabel instance to view.
Updated for Swift 3
import UIKit
class ViewController: UIViewController {
let redView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .red
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupAutoLayout()
}
func setupViews() {
view.backgroundColor = .white
view.addSubview(redView)
}
func setupAutoLayout() {
// Available from iOS 9 commonly known as Anchoring System for AutoLayout...
redView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
redView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true
redView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
redView.heightAnchor.constraint(equalToConstant: 300).isActive = true
// You can also modified above last two lines as follows by commenting above & uncommenting below lines...
// redView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
// redView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
}
Type of Constraints:
/*
// regular use
1.leftAnchor
2.rightAnchor
3.topAnchor
// intermediate use
4.widthAnchor
5.heightAnchor
6.bottomAnchor
7.centerXAnchor
8.centerYAnchor
// rare use
9.leadingAnchor
10.trailingAnchor
etc. (note: very project to project)
*/

How can I add same uiview multiples times at different positions to a UIViewController?

I am trying to achieve this in swift.
So far I created my own custom view which is a subclass of UIView class:
class MyConnections: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 1)
CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
let circle = CGRectMake(5, 60, 80, 80)
CGContextAddEllipseInRect(context, circle)
CGContextStrokePath(context)
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextFillEllipseInRect(context, circle)
}
}
This is my view controller where I add the above view as a subview:
let profile = MyConnections()
override func viewDidLoad() {
super.viewDidLoad()
profile.backgroundColor = UIColor.clearColor()
view.addSubview(profile)
self.profile.setTranslatesAutoresizingMaskIntoConstraints(false)
//constraints for the location button
let horizontalConstraint = NSLayoutConstraint(item: self.profile, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 10)
let verticalConstraint = NSLayoutConstraint(item: self.profile
, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 20)
let widthConstraint = NSLayoutConstraint(item: self.profile, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 150)
let heightConstraint = NSLayoutConstraint(item: self.profile, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 150)
self.view.addConstraints([verticalConstraint, horizontalConstraint, widthConstraint, heightConstraint])
// Do any additional setup after loading the view.
}
All the code above gives me a circle on top. Now I want to repeat that same circle multiple times at different positions as seen in the image. I can create multiple instances of the uiview add them as subview but every time I will have to define new constraints for it which I don't want to do.
Can anyone please help me and give me an efficient answer?
You should know a UIView can have a single superview/parent. If you add it as a subview at a different position (using addSubview method) it will be removed from the first position and added as a subview to the new position.
In your case to add more subviews you have to create more UIView objects not use a single global UIView.
If the layout is repetitive a UITableView / UICollectionView is a better choice.
Your requirement and UI qualify for a UICollectionView I think you should use UICollectionView and can create a custom UICollectionViewCell with round image and and badge view as well, and they add dataSource and delegate methods. That will not only help in creating UI but it will make your app more performant by reusing cells
Here is a nice tutorial about UICollectionView
Here's a simplified view to create collection view programmatically:
make the collection view and layout programmatically just like any other view you would code and add it as subview like below:
lazy var myCollectionView : UICollectionView = {
let layout = YourFlowLayout()
layout.scrollDirection = self.direction;
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
cv.dataSource = self
cv.delegate = self
cv.isPagingEnabled = true
cv.backgroundColor = UIColor.clear
cv.showsHorizontalScrollIndicator = false
cv.showsVerticalScrollIndicator = false
cv.allowsMultipleSelection = false
return cv
}()
and your flow layout could be something like:
mport UIKit
class Yourflowlayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return super.layoutAttributesForElements(in: rect)?.map {
attrs in
let attrscp = attrs.copy() as! UICollectionViewLayoutAttributes
self.applyLayoutAttributes(attributes: attrscp)
return attrscp
}
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if let attrs = super.layoutAttributesForItem(at: indexPath as IndexPath) {
let attrscp = attrs.copy() as! UICollectionViewLayoutAttributes
self.applyLayoutAttributes(attributes: attrscp)
return attrscp
}
return nil
}
func applyLayoutAttributes(attributes : UICollectionViewLayoutAttributes) {
if attributes.representedElementKind != nil {
return
}
if let collectionView = self.collectionView {
let stride = (self.scrollDirection == .horizontal) ? collectionView.frame.size.width : collectionView.frame.size.height
let offset = CGFloat(attributes.indexPath.section) * stride
var xCellOffset : CGFloat = CGFloat(attributes.indexPath.item) * self.itemSize.width
var yCellOffset : CGFloat = CGFloat(attributes.indexPath.item) * self.itemSize.height
if(self.scrollDirection == .horizontal) {
xCellOffset += offset;
} else {
yCellOffset += offset
}
attributes.frame = CGRect(x: xCellOffset, y: yCellOffset, width: self.itemSize.width, height: self.itemSize.height)
}
}
}
You can add the collectionView in your other classes as a subview , make sure you have the
myCollectionView.translatesAutoresizingMaskIntoConstraints = false so that your constrains are applied and you actually see the collection view and of course add your constrains or give it a frame.
Hope that helps someone.

Resources