How to make vertical labels bar in Swift? - swift

I would like to make such layout via swift:
I tried to make it in such way:
var buttonArray = [UILabel]()
for (myKey,myValue) in colorDictionary{
buttonArray += [colorButton(withColor: myValue, title: myKey)]
}
let horizontalStack = UIStackView(arrangedSubviews: buttonArray)
horizontalStack.axis = .horizontal
horizontalStack.distribution = .fillEqually
horizontalStack.alignment = .fill
horizontalStack.translatesAutoresizingMaskIntoConstraints = false
horizontalStack.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
let label2 = UILabel()
label2.text = "Label"
label2.backgroundColor = .red
label2.textColor = .white
label2.textAlignment = .center
label2.lineBreakMode = .byCharWrapping
label2.numberOfLines = 0
label2.translatesAutoresizingMaskIntoConstraints = false
label2.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
let mainStackView = UIStackView()
mainStackView.axis = .horizontal
mainStackView.translatesAutoresizingMaskIntoConstraints = false
mainStackView.addArrangedSubview(label2)
mainStackView.addArrangedSubview(horizontalStack)
mainContainer.addSubview(mainStackView)
NSLayoutConstraint.activate([
mainStackView.topAnchor.constraint(equalTo: mainContainer.topAnchor, constant: 5),
mainStackView.leftAnchor.constraint(equalTo: mainContainer.leftAnchor,
constant: 20),
mainStackView.rightAnchor.constraint(equalTo: mainContainer.rightAnchor,
constant: -20),
mainStackView.heightAnchor.constraint(equalToConstant: 270),
])
where colorButton is:
func colorButton(withColor color:UIColor, title:String) -> UILabel{
let newButton = UILabel()
newButton.backgroundColor = color
newButton.text = title
newButton.textAlignment = .center
newButton.textColor = UIColor.white
return newButton
}
and here is the result which I got:
How I can make all these labels look like the desired image? And also I'm not sure whether label rotation can be done by my method.

What I would do is first get it working without any transformations so it appears as a normal, not rotated setup. Once that is working, you only need to apply a single transformation to the main stack view to get the whole thing rotated. Then finally you can tweak the constraints to get it positioned correctly.
Here is code that works:
let horizontalStack = UIStackView(arrangedSubviews: buttonArray)
horizontalStack.axis = .horizontal
horizontalStack.distribution = .fillEqually
horizontalStack.alignment = .fill
horizontalStack.translatesAutoresizingMaskIntoConstraints = false
let label2 = UILabel()
label2.text = "Label"
label2.backgroundColor = .red
label2.textColor = .white
label2.textAlignment = .center
label2.lineBreakMode = .byCharWrapping
label2.numberOfLines = 0
label2.translatesAutoresizingMaskIntoConstraints = false
let mainStackView = UIStackView()
mainStackView.axis = .vertical
mainStackView.distribution = .equalSpacing
mainStackView.translatesAutoresizingMaskIntoConstraints = false
mainStackView.addArrangedSubview(label2)
mainStackView.addArrangedSubview(horizontalStack)
mainStackView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
mainContainer.addSubview(mainStackView)
NSLayoutConstraint.activate([
mainStackView.centerYAnchor.constraint(equalTo: mainContainer.centerYAnchor),
mainStackView.centerXAnchor.constraint(equalTo: mainContainer.leftAnchor, constant: 40),
// Set the "width", not the "height"
mainStackView.widthAnchor.constraint(equalToConstant: 270),
])
Changes:
I removed the transformation you had for the horizontal stack view and the big label.
I added a single transformation to the main stack view.
I used a vertical, not horizontal, stack view for the main stack.
Updated the properties of the main stack view so the main label fills the area above the other labels.
Updated the constraints. Adjust those to suit your needs.
Note that you need to set the width of the main stack view since the constraint is relative to the untransformed main stack view.

Related

UILabel is not replacing previous text when view refreshed

I have the following function being called in a ViewController that passes in data to build a list of transactions. Each time the page refreshes, this is called and new data is shown. All is good, except for one remaining frustrating bug: when the new data is loaded the previous balancedOwedAmountLabel.text still shows the previous amount.
So on each refresh, the text is written on top of the previous text each time. This results in a jumbled mess of text each time the page is refreshed. It would be expected to have the previous text removed, and replaced with the new text that I determine.
I've tried manually setting the balancedOwedAmountLabel.text = nil to simply remove it and then reset it each time the data is retrieved and painted, but it won't work. I've also tried removing the subview entirely via balancedOwedAmountLabel.removeFromSuperview() and that doesn't seem to do the trick either.
Since I'm not using a Storyboard I can't connect IBOutlets so I'm having to resort to figuring out how to get around this problem programmatically. How do I go about solving this with the following code?
private func buildTransactionTableView() {
let stackview = UIStackView()
stackview.axis = .vertical
stackview.distribution = .fill
stackview.spacing = 15
self.view.insertSubview(stackview, belowSubview: (self.accountSummaryTableViewController?.view)!)
stackview.translatesAutoresizingMaskIntoConstraints = false
stackview.topAnchor.constraint(equalTo: self.transactionsTableView.bottomAnchor, constant: 0).isActive = true
stackview.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10).isActive = true
stackview.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -10).isActive = true
stackview.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,constant: -30).isActive = true
// full width parent SV
let headlineStackView = UIStackView()
headlineStackView.axis = .horizontal
headlineStackView.alignment = .top
headlineStackView.distribution = .fill
let titleLabel = UILabel(frame: CGRect(x:0,y:0,width:200,height:21))
titleLabel.textAlignment = .left
titleLabel.textColor = .black
titleLabel.font = UIFont.boldSystemFont(ofSize: 14.00)
titleLabel.text = "Transaction History"
headlineStackView.addArrangedSubview(titleLabel)
stackview.addArrangedSubview(headlineStackView)
// SV for balance informations
let balanceStackView = UIStackView()
balanceStackView.axis = .horizontal
balanceStackView.distribution = .fill
headlineStackView.addArrangedSubview(balanceStackView)
let balanceOwedLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
balanceOwedLabel.textAlignment = .right
balanceOwedLabel.textColor = .black
balanceOwedLabel.font = balanceOwedLabel.font.withSize(14.00)
balanceOwedLabel.text = "Balance Owed"
balanceStackView.addArrangedSubview(balanceOwedLabel)
let balancedOwedAmountLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
balancedOwedAmountLabel.textAlignment = .right
balancedOwedAmountLabel.textColor = UIColor(red: 33.00/255, green: 150.00/255, blue: 243.00/255, alpha: 1.00)
balancedOwedAmountLabel.font = UIFont.boldSystemFont(ofSize: 14.00)
var amount = 0.00
for rtp in self.userTransactions! {
if rtp.repaymentDate == nil && rtp.rtpData.amount.value != nil {
let value = Double((rtp.rtpData.amount.value)!)
amount = amount + value!
}
}
balanceStackView.addArrangedSubview(balancedOwedAmountLabel)
// This amount overwrites previous amount on screen when refreshed
// The amount is not being removed and replaced wih this new amount
balancedOwedAmountLabel.text = " $\(String(format: "%.2f", amount))"
let rtpTableVC = UserTransactionsTableViewController(style: .plain)
rtpTableVC.tableView.allowsSelection = false
rtpTableVC.tableView.separatorStyle = .none
rtpTableVC.tableView.isScrollEnabled = true
rtpTableVC.rtpTransactions = self.rtpTransactions
stackview.addArrangedSubview(rtpTableVC.view)
self.userTransactionsTableViewController = rtpTableVC
}
}
It looks like each time this function is called, you create a new stackview and add it in self.view. But I cannot see when you remove previous stackview?
One way of fixing it would be: store reference on current stackview and remove it before adding new one as:
var currentStackView: UIStackView?
private func buildTransactionTableView() {
currentStackView.removeFromSupperView()
let stackview = UIStackView()
currentStackView = stackview
...
}

Altered column width in horizontal UIStackview

I have a 4 x 1 UILabel matrix in a horizontal stackview I would like columns 1 and 3 to be the same width BUT narrower than columns 2 and 4. I have tried .fillproportionally, and others. I understood that this was possible... however, a solution evades me and Google hasn't turned anything up. Any help or a point in the right direction would be helpful. Thank you. I am not using Storyboards.
You can create your grid:
as you described:
C1-w == 1/3 of C2-w
C3-w == C1-w
C4-w == C2-w
pretty much with that description:
with the stack view .distribution = .fill
Here's a complete example:
class ColumnStackViewController: UIViewController {
let outerStack: UIStackView = {
let v = UIStackView()
v.translatesAutoresizingMaskIntoConstraints = false
v.axis = .vertical
v.alignment = .fill
v.distribution = .fill
v.spacing = 8
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
// create "header row" stack view
let headerRowStack = UIStackView()
headerRowStack.axis = .horizontal
headerRowStack.spacing = 4
// create 4 labels for header row
let headerC1 = UILabel()
let headerC2 = UILabel()
let headerC3 = UILabel()
let headerC4 = UILabel()
headerC1.text = "C1"
headerC2.text = "C2"
headerC3.text = "C3"
headerC4.text = "C4"
[headerC1, headerC2, headerC3, headerC4].forEach { v in
// give each "header" label a background color, so we can see the frames
v.backgroundColor = .yellow
v.textAlignment = .center
headerRowStack.addArrangedSubview(v)
}
NSLayoutConstraint.activate([
// constrain c1 width to 1/3 of c2 width
headerC1.widthAnchor.constraint(equalTo: headerC2.widthAnchor, multiplier: 1.0 / 3.0),
// constrain c3 width equal to c1 width
headerC3.widthAnchor.constraint(equalTo: headerC1.widthAnchor),
// constrain c4 width equal to c2 width
headerC4.widthAnchor.constraint(equalTo: headerC2.widthAnchor),
])
outerStack.addArrangedSubview(headerRowStack)
let c1Vals = ["HOLDING", "BOOK", "P/L"]
let c3Vals = ["PAID", "MARKET", "WEIGHT"]
for i in 0..<c1Vals.count {
// create a "row" stack view
let rowStack = UIStackView()
rowStack.axis = .horizontal
rowStack.spacing = headerRowStack.spacing
// add it to outer stack view
outerStack.addArrangedSubview(rowStack)
let rowC1 = UILabel()
let rowC2 = UILabel()
let rowC3 = UILabel()
let rowC4 = UILabel()
rowC1.text = c1Vals[i]
rowC3.text = c3Vals[i]
rowC2.text = "row \(i+1) c2 data"
rowC4.text = "row \(i+1) c4 data"
[rowC1, rowC2, rowC3, rowC4].forEach { v in
// give each row-label a border
v.layer.borderColor = UIColor.red.cgColor
v.layer.borderWidth = 0.5
// set the font
v.font = UIFont.systemFont(ofSize: 14.0, weight: .light)
// add it to the row stack view
rowStack.addArrangedSubview(v)
}
// constrain each row-label width to the header-row label width
for (hLabel, rowLabel) in zip([headerC1, headerC2, headerC3, headerC4], [rowC1, rowC2, rowC3, rowC4]) {
rowLabel.widthAnchor.constraint(equalTo: hLabel.widthAnchor).isActive = true
}
}
view.addSubview(outerStack)
// respect safe area
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// constrain outer stack view to Top / Leading / Trailing with 20-pt "padding"
outerStack.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
outerStack.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
outerStack.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
])
}
}
which produces this result:
Note: you'll have to use a pretty small font to fit that layout on a small device:
This is all i ended needing v1.widthAnchor.constraint(equalTo: v2.widthAnchor, multiplier: 0.5, constant: 0).isActive = true v3.widthAnchor.constraint(equalTo: v1.widthAnchor ).isActive = true v4.widthAnchor.constraint(equalTo: v2.widthAnchor ).isActive = true

Horizontal Stackview left align items

I am creating a horizontal UIStackView and want to left align items in it.
Here is my code:
let nameLabel: UILabel = {
let label=UILabel()
label.text = "First Name:"
label.textColor = UIColor.black
label.font = UIFont.systemFont(ofSize: 20)
label.textAlignment = .left
label.translatesAutoresizingMaskIntoConstraints=false
return label
}()
let nameTextField: UITextField = {
let label=UITextField()
label.placeholder = "Enter Name"
label.textColor = UIColor.darkGray
label.font = UIFont.systemFont(ofSize: 18)
label.textAlignment = .left
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints=false
return label
}()
lazy var firstNameView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [self.nameLabel, self.nameTextField])
stackView.translatesAutoresizingMaskIntoConstraints = false;
stackView.axis = .horizontal
stackView.distribution = .fill
stackView.alignment = .center
stackView.spacing = 10.0
return stackView
}()
And here is how i add it to the view
self.view.addSubview(firstNameView)
firstNameView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true;
firstNameView.topAnchor.constraint(equalTo: idLabel.bottomAnchor).isActive = true;
firstNameView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
firstNameView.heightAnchor.constraint(equalToConstant: 40.0).isActive = true
I also tried the following:
firstNameView.trailingAnchor.constraint(greaterThanOrEqualTo: self.view.trailingAnchor).isActive = true
PS: This question is different from UIStackview align left as i am talking about horizontal stackview
According to this link Left aligned horizontal stackview and top aligned vertical stackview
Is there any alternative, i don't really want to set a fixed width.
Wrap your labels in UIViews and pin the labels to the left of these views. Put the views into the stack view and they will fill the stack view without manipulating the labels.

label showing top of screen instead of being on the inputAccessoryView

Here is my code:
var messageView : UITextView = {
var textView = UITextView()
textView.text = " Add your message here"
textView.textColor = UIColor.lightGrayColor()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.backgroundColor = UIColor.lightGrayColor()
textView.layer.cornerRadius = 3
textView.clipsToBounds = true
textView.keyboardAppearance = .Dark
textView.layer.borderWidth = 1.0
textView.layer.borderColor = UIColor.lightGrayColor()
textView.autocorrectionType = .no
// MARK: Setup accesorryView
let label = UILabel()
label.text = "You have a 100 character limit"
label.translatesAutoresizingMaskIntoConstraints = false
let accessoryView = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 44))
accessoryView.backgroundColor = UIColor.redColor()
accessoryView.addSubview(label)
accessoryView.leadingAnchor.constraintEqualToAnchor(label.leadingAnchor, constant: 18)
accessoryView.centerYAnchor.constraintEqualToAnchor(label.centerYAnchor)
textView.inputAccessoryView = accessoryView
return textView
}()
I'm trying to add an inputAccessoryView to my TextView's keyboard.
My inputAccessoryView must have a label saying "You have a 100 character limit"...
But my current result is as:
The text in the blue...is exactly the label I want to be in the inputAccessoryView, but it's on the top of my screen...
You need to set translatesAutoresizingMaskIntoConstraints on the label to false and isActive to true on the constraints. Basically your constrains code should look like this:
accessoryView.leadingAnchor.constraintEqualToAnchor(label.leadingAnchor, constant: 18).isActive = true
accessoryView.centerYAnchor.constraintEqualToAnchor(label.centerYAnchor).isActive = true
As per my understanding, try this:
Swift 3
let accessoryView = UIView()
let label = UILabel()
let counterLabel = UILabel()//This is the counter label
label.text = "You have a 100 character limit"
counterLabel.text = "100"
accessoryView.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44)
accessoryView.backgroundColor = UIColor.red
accessoryView.addSubview(label)
accessoryView.addSubview(counterLabel)
// to setup contraint set below property to false.
label.translatesAutoresizingMaskIntoConstraints = false
counterLabel.translatesAutoresizingMaskIntoConstraints = false
//label constrint with 0 padding from left side. To change padding from left and right side, change the constant value.
accessoryView.leadingAnchor.constraint(equalTo: label.leadingAnchor, constant: 0).isActive = true
accessoryView.centerYAnchor.constraint(equalTo: label.centerYAnchor).isActive = true
//counterl=Label constrint with 0 padding from right side
accessoryView.trailingAnchor.constraint(equalTo:counterLabel.trailingAnchor, constant: 0).isActive = true
accessoryView.centerYAnchor.constraint(equalTo: counterLabel.centerYAnchor).isActive = true
textView.inputAccessoryView = accessoryView

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()
})
}
}