Swift: Make vertical scrolling feed with programmatically sized UIViews - ios

I'm building a scrolling feed in my app with data grabbed from a database (firebase). I'm not very experienced in Swift as most of the stuff I do is web design. What I'm looking for is a good way to size the height of my UIViews. Here is what I currently have (fixed height):
Here's my code UIView class:
class eventView: UIView {
let eventDate : UILabel = {
let eventDate = UILabel()
eventDate.translatesAutoresizingMaskIntoConstraints = false
eventDate.numberOfLines = 0
eventDate.textAlignment = .center
return eventDate
}()
let eventTitle : UILabel = {
Same thing as eventDate
}()
let eventDesc : UILabel = {
same thing as eventDate
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.lightGray
self.layer.cornerRadius = 10
self.addSubview(eventDate)
eventDate.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
eventDate.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
self.addSubview(eventTitle)
eventTitle.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
eventTitle.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
eventTitle.topAnchor.constraint(equalTo: eventDate.bottomAnchor).isActive = true
self.addSubview(eventDesc)
eventDesc.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
eventDesc.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
eventDesc.topAnchor.constraint(equalTo: eventTitle.bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Here is my for list that displays these UIViews:
var i = 0
for data in self.eventViewData {
let view = eventView(frame: CGRect(x: 0, y: ( CGFloat(170 * i)), width: self.scrollView.frame.width - 20, height: CGFloat(150)))
view.center.x = self.scrollView.center.x
view.eventDate.text = data.date
view.eventTitle.text = data.title
view.eventDesc.text = data.description
self.scrollView.addSubview(view)
i += 1
}
I usually am using HTML div's and such so I'm having a hard time figuring out how to style these. Any information or links to tutorials on how to programmatically adjust constraints to the UILabels in my eventViews are also appreciated.

How to calculate the desired height seems to be the question. While there are a lot of ways to do this one approach would be something like this:
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
let font = UIFont(name: "Helvetica", size: 20.0)
var height = heightForView("This is just a load of text", font: font, width: 100.0)
// apply height to desired view
I prefer to put the heightForView function in an extension myself but it isn't required.

I assumed you're using table view, why not do dynamic height? Good reference https://www.raywenderlich.com/1067-self-sizing-table-view-cells
In essense, you use auto layout to define your top and bottom constraint accordingly for every element in your cell, and your table view delegation/data source method for heightforrow and estimatedheightforrow, return UITableViewAutomaticDimension

Related

How can I add some insets to the text inside the UILabel?

I'm trying to add insets to the text inside the UILabel without subclassing it. Or even with UILabel subclass but without changing too much the code.
How can I do it?
class CustomCell: UICollectionViewCell {
var data:CustomData? {
didSet {
guard let data = data else { return }
//bg.image = data.image
bg.text = data.title
}
}
fileprivate let bg: UILabel = {
let iv = UILabel()
iv.layer.backgroundColor = UIColor.gray.cgColor
iv.textAlignment = .center
iv.numberOfLines = 0
iv.font = UIFont(name: "Helvetica", size: 40)
iv.adjustsFontSizeToFitWidth = true
iv.minimumScaleFactor = 0.5
iv.translatesAutoresizingMaskIntoConstraints = false
iv.layer.cornerRadius = 12
return iv
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(bg)
bg.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
bg.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
bg.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
bg.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Use constant parameter
bg.topAnchor.constraint(equalTo: contentView.topAnchor,constant:30).isActive = true
for 30 pts inset do
NSLayoutConstraint.activate([
bg.topAnchor.constraint(equalTo: contentView.topAnchor,constant:30),
bg.leadingAnchor.constraint(equalTo: contentView.leadingAnchor,constant:30),
bg.trailingAnchor.constraint(equalTo: contentView.trailingAnchor,constant:-30),
bg.bottomAnchor.constraint(equalTo: contentView.bottomAnchor,constant:-30)
])
You can also set UIEdgeInsets
Your entire approach is wrong. If the goal is to show the label text centered in bg, then bg should not be a label; it should contain a label, centered.
This example uses no code at all; the outer view self-sizes to the label, and the label's constraints to the outer view provide the insets:

Custom UITextField with UILabel multiline support for error text

I want to create custom UITextField with error label on bottom of it. I want the label to be multiline, I tried numberOfLines = 0. But it is not working.
Here is my snippet for the class
public class MyTextField: UITextField {
private let helperTextLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12.0, weight: UIFont.Weight.regular)
label.textColor = helperTextColor
label.numberOfLines = 0
return label
}()
public override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(errorTextLabel)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addSubview(errorTextLabel)
}
public override func layoutSubviews() {
super.layoutSubviews()
errorTextLabel.frame = CGRect(x: bounds.minX, y: bounds.maxY - 20, width: bounds.width, height: 20)
}
public override var intrinsicContentSize: CGSize {
return CGSize(width: 240.0, height: 68.0)
}
public override func sizeThatFits(_ size: CGSize) -> CGSize {
return intrinsicContentSize
}
}
I think the root cause is because I set height to 20, but how can I set the height dynamically based on the errorTextLabel.text value?
You are giving your label a fixed size.
Not using AutoLayout and giving the textfield and label room to expand it's size when needed.
Personally, if creating this particular control, I would create a UIView with a textfield and a label inside a UIStackView. That way if the label is hidden when there is no error the stackview will automatically adjust the height for you. Then when you unhide it, the view will expand to fit both controls.
A basic example:
//: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
class LabelledTextView: UIView {
private let label = UILabel()
private let textfield = UITextField()
private let stackView = UIStackView()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: topAnchor).isActive = true
stackView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
stackView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
stackView.alignment = .leading
stackView.axis = .vertical
stackView.distribution = .fillEqually
stackView.addArrangedSubview(textfield)
stackView.addArrangedSubview(label)
textfield.placeholder = "Please enter some text"
label.numberOfLines = 0
label.text = "Text did not pass validation, Text did not pass validation, Text did not pass validation, Text did not pass validation"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
let labelledTextView = LabelledTextView(frame: CGRect(x: 50, y: 300, width: 300, height: 60))
let vc = UIViewController()
vc.view.addSubview(labelledTextView)
labelledTextView.translatesAutoresizingMaskIntoConstraints = false
labelledTextView.topAnchor.constraint(equalTo: vc.view.topAnchor).isActive = true
labelledTextView.leftAnchor.constraint(equalTo: vc.view.leftAnchor).isActive = true
labelledTextView.widthAnchor.constraint(equalToConstant: 300).isActive = true
labelledTextView.heightAnchor.constraint(greaterThanOrEqualToConstant: 60).isActive = true
PlaygroundPage.current.liveView = vc.view
You need to use sizeToFit():
errorTextLabel.sizeToFit()

Multiline UIButton with each line truncated independently

I'm trying to make a multiline button by subclassing UIButton. To avoid drawing two custom UILabel (I'm still pretty new to Swift/Xcode), I'm using attributed strings for the existing UILabel and splitting lines with a new line character, like so:
func prepareAttributedTitle(_ primaryTitle: String = "", _ secondaryTitle: String = "") {
let title = NSMutableAttributedString()
let first = NSAttributedString(string: primaryTitle, attributes: [
NSForegroundColorAttributeName: tintColor,
NSFontAttributeName: UIFont.systemFont(ofSize: UIFont.systemFontSize, weight: UIFontWeightSemibold)
])
let newLine = NSAttributedString(string: "\n")
let second = NSAttributedString(string: secondaryTitle, attributes: [
NSForegroundColorAttributeName: tintColor.withAlphaComponent(0.75),
NSFontAttributeName: UIFont.systemFont(ofSize: UIFont.smallSystemFontSize)
])
title.append(first)
title.append(newLine)
title.append(second)
setAttributedTitle(title, for: .normal)
}
And the result is (sorry, I don't have enough rep to post images):
| This is the long first |
| line |
| Secondary line |
However, I'd like to truncate lines independently, like this:
| This is the long fi... |
| Secondary line |
Is there a way to do this without using two custom UILabels?
Thanks
A single UILabel does not support what you need. You will have to use two single-line labels each set with tail truncation.
I'm answering my own question with what worked for me. Here's my subclass of UIButton, but keep in mind I'm not an experienced developer. There's also some styling and support for the tint color:
import UIKit
#IBDesignable
class FilterButton: UIButton {
let primaryLabel = UILabel()
let secondaryLabel = UILabel()
#IBInspectable var primaryTitle = "" {
didSet {
primaryLabel.text = primaryTitle
}
}
#IBInspectable var secondaryTitle = "" {
didSet {
secondaryLabel.text = secondaryTitle
}
}
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
override func prepareForInterfaceBuilder() {
primaryTitle = "Primary title"
secondaryTitle = "Secondary title"
commonInit()
}
func commonInit() {
// Force left alignment (FIXME: Use user language direction)
contentHorizontalAlignment = .left
// Set some padding and styling
contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
layer.cornerRadius = 5
layer.borderWidth = 1
// Hide button original label
titleLabel?.isHidden = true
// Prepare the primary label
primaryLabel.frame = CGRect(x: contentEdgeInsets.left,
y: contentEdgeInsets.top,
width: frame.width - contentEdgeInsets.left - contentEdgeInsets.right,
height: (frame.height - contentEdgeInsets.top - contentEdgeInsets.bottom) / 2)
primaryLabel.font = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)
primaryLabel.textColor = tintColor
// primaryLabel.backgroundColor = UIColor.green // For debugging
primaryLabel.lineBreakMode = .byTruncatingMiddle // Truncate first line
primaryLabel.autoresizingMask = .flexibleWidth
addSubview(primaryLabel)
// Prepare the secondary label
secondaryLabel.frame = CGRect(x: contentEdgeInsets.left,
y: contentEdgeInsets.top + primaryLabel.frame.height,
width: frame.width - contentEdgeInsets.left - contentEdgeInsets.right,
height: (frame.height - contentEdgeInsets.top - contentEdgeInsets.bottom) / 2)
secondaryLabel.font = UIFont.systemFont(ofSize: UIFont.smallSystemFontSize)
secondaryLabel.textColor = tintColor.withAlphaComponent(0.75)
// secondaryLabel.backgroundColor = UIColor.yellow // For debugging
secondaryLabel.lineBreakMode = .byTruncatingMiddle // Truncate second line
secondaryLabel.autoresizingMask = .flexibleWidth
addSubview(secondaryLabel)
primaryLabel.text = primaryTitle
secondaryLabel.text = secondaryTitle
}
// Support tint color
override func tintColorDidChange() {
super.tintColorDidChange()
layer.borderColor = tintColor.cgColor
layer.backgroundColor = tintColor.withAlphaComponent(0.05).cgColor
primaryLabel.textColor = tintColor
secondaryLabel.textColor = tintColor.withAlphaComponent(0.75)
}
}

Programmatically moving UILabel not working

I am having trouble changing the position of my UILabel. I can change font color and background etc but its position doesn't seem to move no matter what I try. Any help would be appreciated. Im also not using storyboard at all.
I'm fairly new to this so I'm probably missing something very obvious. I have googled and tried anything I thought applied but haven't had any luck.
View Builder:
import UIKit
class StandMapView: UIView {
var titleLabel: UILabel = UILabel()
var standMapImage: UIImageView = UIImageView()
var hotspotImage: UIImageView = UIImageView()
var hotspotTitleLabelArray: [UILabel] = []
var hotspotTextArray: [UITextView] = []
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bind(standMap: StandMap, hotspots: [Hotspot]) {
titleLabel.text = standMap.title
standMapImage.image = UIImage(named: standMap.mapImage)
hotspotImage.image = UIImage(named:standMap.hotspotImage)
for hotspot in hotspots {
let hotspotTitle = UILabel()
let hotspotText = UITextView()
hotspotTitle.text = hotspot.title
hotspotText.text = hotspot.text
hotspotTitleLabelArray.append(hotspotTitle)
hotspotTextArray.append(hotspotText)
}
}
private func setupView() {
let screenWidth = UIScreen.mainScreen().bounds.width
let screenHeight = UIScreen.mainScreen().bounds.height
self.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
standMapImage.translatesAutoresizingMaskIntoConstraints = false
hotspotImage.translatesAutoresizingMaskIntoConstraints = false
self.backgroundColor = UIColor.blackColor()
titleLabel.sizeToFit()
titleLabel.frame = CGRect(x: screenWidth/2, y: 30, width: 0, height: 0)
titleLabel.textAlignment = .Center
titleLabel.numberOfLines = 0
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.textColor = UIColor.whiteColor()
addSubview(titleLabel)
}
}
View Controller:
import UIKit
class StandMapViewController: UIViewController {
var standMap: StandMap!
var hotspots: [Hotspot] = []
override func viewDidLoad() {
super.viewDidLoad()
Hotspot.all { hotspot in
hotspot.forEach(self.assignHotspotVariable)
}
StandMap.build {standMap in
standMap.forEach(self.assignStandMapVariable)
}
viewForStandMap(standMap, hotspots: hotspots)
}
private func assignStandMapVariable(standMap: StandMap) {
self.standMap = standMap
}
private func assignHotspotVariable(hotspot: Hotspot) {
hotspots.append(hotspot)
}
private func viewForStandMap(standMap: StandMap, hotspots: [Hotspot]) {
let standMapView = StandMapView(frame: CGRectZero)
standMapView.bind(standMap, hotspots: hotspots)
view.addSubview(standMapView)
}
}
If you want to change the position of the label, you need to change the origin x and y
titleLabel.frame.origin.x = 0.0 // put your value
titleLabel.frame.origin.y = 0.0 // put your value
self.view.layoutIfNeeded()
I managed to solve this using snapkit cocoa pod to make the constraints and then adding the subview before declaring these constraints.
Thanks for everyones help.
Heres the changes i made to the setupView function:
private func setupView() {
titleLabel.translatesAutoresizingMaskIntoConstraints = false
standMapImage.translatesAutoresizingMaskIntoConstraints = false
hotspotImage.translatesAutoresizingMaskIntoConstraints = false
self.backgroundColor = UIColor.blackColor()
titleLabel.textColor = UIColor.whiteColor()
titleLabel.textAlignment = .Center
titleLabel.numberOfLines = 0
titleLabel.adjustsFontSizeToFitWidth = true
addSubview(titleLabel)
titleLabel.snp_makeConstraints { make in
make.topMargin.equalTo(snp_topMargin).multipliedBy(60)
make.centerX.equalTo(snp_centerX)
}
}
If your label has constraints with Autolayout in storyboard, you must disable constraints to move the frame. Try using
titleLabel.translatesAutoresizingMaskIntoConstraints = YES;
Hope this may solve your issue.
If you are using AutoLayout, do following:
set outlet for constraint of UILable that you want to change.
Then change constant of that constraint as per your need.
e.g: xPosOfLable.constant = x

UILabel resizes its SuperView?

I have the following view which contains a UILabel:
class MyView : UIView {
func viewDidLoad() {
self.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
bottomView = UIView(frame: CGRectMake(self.bounds.origin.x, self.bounds.origin.y + self.imageView!.bounds.size.width, self.bounds.size.width, self.bounds.size.height - self.imageView!.bounds.size.height))
// bottomView frame calculation is: (0.0, 355.0, 355.0, 130.0)
bottomView?.backgroundColor = UIColor.greenColor()
bottomView?.autoresizingMask = UIViewAutoresizing.FlexibleWidth
bottomView?.clipsToBounds = true
self.addSubview(self.bottomView!)
var descriptionRect: CGRect = CGRectInset(self.bottomView!.bounds, leftRightInset, 20/2)
let descriptionLabel = UILabel()
descriptionLabel.numberOfLines = 3
descriptionLabel.autoresizingMask = UIViewAutoresizing.FlexibleWidth
descriptionLabel.font = UIFont(name: MGFont.helvetica, size: 22)
descriptionLabel.textColor = UIColor.whiteColor()
descriptionLabel.textAlignment = NSTextAlignment.Left
descriptionLabel.backgroundColor = UIColor.blueColor()
var paragraphStyle:NSMutableParagraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1.0
paragraphStyle.lineBreakMode = NSLineBreakMode.ByTruncatingTail
let attributes = [NSParagraphStyleAttributeName : paragraphStyle]
descriptionLabel.attributedText = NSAttributedString(string: previewCard.title, attributes:attributes)
bottomView?.addSubview(descriptionLabel)
descriptionLabel.bounds = descriptionRect
descriptionLabel.sizeToFit()
descriptionLabel.center = CGPointMake(bottomView!.bounds.width/2, bottomView!.bounds.height/2 - hotelNameLableHeight/2)
}
}
The height of the bottomView should always be fixed.
MyView is resized during runtime. This means that the green bottom view also increases in size.
Here is the result when the label has two and three lines:
It appears that the UILabel resizes its super view.
Note that I do not use AutoLayout.
override func layoutSubviews() {
super.layoutSubviews()
}
How can I prevent the UILabel from resizing its SuperView?
Edit: I also tried to comment bottomView?.clipsToBounds = true
Override setFrame: and setBounds: of the super view (subclass if they're plain UIViews), add breakpoints, and see the stack trace to find out what's causing them to resize.
There is no need to set the autoResizingMask on the label, just set the frame and it will get automatically centered. And of course you can set the insets for the UILabel accordingly. I've add below testing code FYI:
override func viewDidLayoutSubviews() {
addTestView(CGRectMake(0, 200, view.bounds.width, 50), labelStr: "I am a short testing label")
addTestView(CGRectMake(0, 260, view.bounds.width, 50), labelStr: "I am a very longlonglonglonglonglonglong testing label")
addTestView(CGRectMake(0, 320, view.bounds.width, 50), labelStr: "I am a very longlonglonglonglonglonglonglonglonglonglonglong testing label. Will be truncated")
}
func addTestView(frame:CGRect, labelStr: String){
let bottomView = UIView(frame:frame)
bottomView.backgroundColor = UIColor.greenColor()
bottomView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
bottomView.clipsToBounds = true
view.addSubview(bottomView)
var label = UILabel(frame: bottomView.bounds)
label.textAlignment = NSTextAlignment.Left
label.numberOfLines = 0
label.text = labelStr
bottomView.addSubview(label)
}

Resources