Organize and adjust the UILabel position per devices - Swift 3 - swift

I have SQLite database file and UILabel, and I set text for label from database on the number of characters after convert String to Characters, and I added extension its name (length), its job counts the number of characters.
My problem in this picture is : The UILabels are not organized in sizes and positions in per devices I want them to have their positions in the center of X-Axis
Questions:
1) How to set the label into center and set spaces right and left of screen for labels (per device) ??
2) How to set width for labels if device is iPhone 7/6S/6 plus width = 50, if device is iPhone 7/6S/6 width = 45 and if device is iPhone SE/5S/5C/5 width = 38 ??
3) Finally, how does the label become smaller by 10 if the number of characters is more than 8 ?
This my code :
func createTarget(id: Int) {
listdata = dbHelpr.getDatabase(rowId: id)
for data in listdata {
let lengthOfChar : CGFloat = data.ans.length
let yAxis : CGFloat = (self.view.frame.height) * 60%
let width: CGFloat = view.frame.size.width - 40 // frame width
var targetWidth: CGFloat = (width - (lengthOfChar - 1) * 5) / lengthOfChar
let targetHeigt : CGFloat = 5
if lengthOfChar >= 8 {
targetWidth = 40
} else {
targetWidth = 50
}
let totalWidth: CGFloat = (targetWidth * lengthOfChar) + ((lengthOfChar - 5) * 5)
for (indexTar, tar) in data.ans.characters.enumerated() {
let x : CGFloat = (width / 2) - (totalWidth / 2)
let xx : CGFloat = (CGFloat(indexTar) * targetWidth) + (CGFloat(indexTar) * 5) + 20
var xAxis : CGFloat = (x + xx)
xAxis = width - xAxis
let targetLabel = UILabel(frame: CGRect(x: xAxis, y: yAxis, width: targetWidth, height: targetHeigt))
targetLabel.backgroundColor = .white
targetLabel.layer.masksToBounds = true
targetLabel.layer.cornerRadius = 5
targetLabel.text = String(describing: tar)
targetLabel.textAlignment = .center
targetLabel.textColor = .white
self.view.addSubview(targetLabel)
}
}
}

In order to position your labels you need a few things things:
Label container to keep everything centered and with margins from the screen sides
Constraints between your labels depending on the device sizes etc..
If you need to break lines - you need to handle it manually as well
To identify device kinds and have different logics, you can check this posts:
iOS: How to determine the current iPhone/device model in Swift?
In order to fill your view with labels, here is a sample code to achieve this:
self.view.backgroundColor = UIColor.black
let labelContainerView : UIView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
labelContainerView.translatesAutoresizingMaskIntoConstraints = false
let containerLeftConstraint : NSLayoutConstraint = NSLayoutConstraint(item: self.view, attribute: .left, relatedBy: .greaterThanOrEqual, toItem: labelContainerView, attribute: .left, multiplier: 1, constant: 8)
let containerRightConstraint : NSLayoutConstraint = NSLayoutConstraint(item: self.view, attribute: .right, relatedBy: .greaterThanOrEqual, toItem: labelContainerView, attribute: .right, multiplier: 1, constant: 8)
let containerCenterX : NSLayoutConstraint = NSLayoutConstraint(item: labelContainerView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
let containerCenterY : NSLayoutConstraint = NSLayoutConstraint(item: labelContainerView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)
self.view.addSubview(labelContainerView)
self.view.addConstraints([ containerLeftConstraint, containerRightConstraint, containerCenterX, containerCenterY ])
// Add some labels
let totalLabels : Int = 10
var lastAddedLabel : UILabel? = nil
for labelAt : Int in 1 ... totalLabels
{
var addedConstraint : [NSLayoutConstraint] = [NSLayoutConstraint]()
let label : UILabel = UILabel(frame: CGRect.zero)
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "_"
label.textColor = UIColor.white
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
if (lastAddedLabel != nil)
{
// Add left constraint to previous label
let leftConstraint : NSLayoutConstraint = NSLayoutConstraint(item: label, attribute: .left, relatedBy: .equal, toItem: lastAddedLabel!, attribute: .right, multiplier: 1, constant: 8)
let equalWidth : NSLayoutConstraint = NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: lastAddedLabel!, attribute: .width, multiplier: 1, constant: 0)
addedConstraint.append(contentsOf: [ leftConstraint, equalWidth ])
}
else
{
// Add left constraint to super view
let leftConstraint : NSLayoutConstraint = NSLayoutConstraint(item: labelContainerView, attribute: .left, relatedBy: .equal, toItem: label, attribute: .left, multiplier: 1, constant: 0)
addedConstraint.append(leftConstraint)
}
// Add top bottom constraint
let topConstraint : NSLayoutConstraint = NSLayoutConstraint(item: labelContainerView, attribute: .top, relatedBy: .equal, toItem: label, attribute: .top, multiplier: 1, constant: 0)
let bottomConstraint : NSLayoutConstraint = NSLayoutConstraint(item: labelContainerView, attribute: .bottom, relatedBy: .equal, toItem: label, attribute: .bottom, multiplier: 1, constant: 0)
addedConstraint.append(contentsOf: [ topConstraint, bottomConstraint ])
// Add right constraint if this is the last label
if (labelAt == totalLabels)
{
let rightConstraint : NSLayoutConstraint = NSLayoutConstraint(item: labelContainerView, attribute: .right, relatedBy: .equal, toItem: label, attribute: .right, multiplier: 1, constant: 0)
addedConstraint.append(rightConstraint)
}
labelContainerView.addSubview(label)
labelContainerView.addConstraints(addedConstraint)
lastAddedLabel = label
}
self.view.layoutIfNeeded()
This gives out the output:
Changes you might need to make:
Change the "totalLabels" number depending on your requirement
Maybe adding another width constraint to the first generated label in order to define a specific with for all labels - the rest of the labels keep the same width as the first
Adjust the containing view margins from both sides for different devices
Handle new lines manually by pre-calculating the width the labels might use.
Good luck

I solved my problem and this answer :
func createTarget(id: Int) {
listdata = dbHelpr.getDatabase(rowId: id)
var targetHeigt = CGFloat()
let viewWidth = self.view.frame.size.width
if viewWidth == 320 {
targetHeigt = 2.5
} else {
targetHeigt = 5
}
for data in listdata {
let yAxis : CGFloat = (self.view.frame.height) * 60%
let i = data.ans.length
// char count
let width: Int = Int(view.frame.size.width) - 40
// frame width
var targetWidth: Int = (width - (i - 1) * 5) / i
if targetWidth > 50 {
targetWidth = 50
}
let totalWidth: Int = (targetWidth * i) + ((i - 1) * 5)
for x in 0..<i {
let currentWidth: Int = (width / 2) - (totalWidth / 2) + (x * targetWidth) + (x * 5) + 20
let targetLabel = UILabel(frame: CGRect(x: CGFloat(currentWidth), y: yAxis, width: CGFloat(targetWidth), height: targetHeigt))
targetLabel.backgroundColor = .white
targetLabel.layer.masksToBounds = true
targetLabel.layer.cornerRadius = 5
targetLabel.textAlignment = .center
targetLabel.textColor = .white
for i in listdata {
let tar = data.ans.characters.map{String($0)}
targetLabel.text = String(describing: tar)
}
self.view.addSubview(targetLabel)
}
}
}

Related

Autolayout ScrollView programmatically swift

I need to set the layout of a ScrollView full-screen with autolayout. at the moment I have this code but not the full-height sect and I can not understand which variable to change. I have this code
func setControlsType(controlsType: ControlsType, bounds: CGRect, startingDim: CGFloat, scrolledDim: CGFloat) {
self.controlsType = controlsType
if Utils.isInPortraitState() {
/*self.startingFrame = CGRect(x: 0, y: bounds.height - startingDim, width: bounds.width, height: scrolledDim)
self.scrolledFrame = CGRect(x: 0, y: bounds.origin.y + bounds.height - scrolledDim, width: bounds.width, height: scrolledDim)*/
self.startingFrame = CGRect(x: 0, y: bounds.height, width: bounds.width, height: scrolledDim)
self.scrolledFrame = CGRect(x: 0, y: bounds.origin.y + bounds.height, width: bounds.width, height: scrolledDim)
} else {
self.startingFrame = CGRect(x: startingDim - scrolledDim, y: 0, width: scrolledDim, height: bounds.height)
self.scrolledFrame = CGRect(x: 0, y: 0, width: scrolledDim, height: bounds.height)
}
func setControls(type: ControlsType) {
let safeBounds = SafeAreaManager.letsDoIt(view: self, upon: .bounds)
/*let sDim = (Utils.isInPortraitState() ? safeBounds.height + (self.workbenchView.frame.origin.y + self.workbenchView.frame.size.height) : safeBounds.width + (self.workbenchView.frame.size.width + self.workbenchView.frame.width))*/
let sDim = CGFloat(0)
var scDim = CGFloat(0)
if Utils.isIPad() {
if Utils.isInPortraitState() {
scDim = safeBounds.height - (self.workbenchView.frame.origin.y + 2 * (self.workbenchView.frame.size.height/3))
} else {
scDim = self.workbenchView.frame.origin.x + self.workbenchView.frame.size.width/3
}
} else {
if Utils.isInPortraitState() {
scDim = safeBounds.height - self.workbenchView.frame.size.height
} else {
scDim = safeBounds.width - self.workbenchView.frame.size.width
}
}
self.controlsView.setControlsType(controlsType: type, bounds: safeBounds, startingDim: sDim, scrolledDim: scDim)
}
It seems that this code is not in your view controller so I see two options among others:
You pass your view and your scroll view to one of your function in the file that you shared above. Then you apply contraints to your scroll view so its frame match your view frame. This function will look like this:
func resizeScrollView(view: UIView, scrollView: UIScrollView) {
NSLayoutConstraint(item: scrollView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: scrollView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: scrollView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: scrollView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0).isActive = true
}
Or you can access the bounds property of the screen of your device via UIScreen and in this case the function will look like this:
func resizeScrollView(scrollView: UIScrollView) {
scrollView.bounds = UIScreen.main.bounds
}
Then you'll have to set the position of your scroll view in your view controller.

translatesAutoresizingMaskIntoConstraints with Charts LineChartView

I'm using LineChartView from Charts in an osx app and I add it as follows to my view:
let lineChartView = LineChartView(frame: NSRect(x: 0, y: 0, width: 300, height: 200))
let ys1 = Array(1..<10).map { x in return sin(Double(x) / 2.0 / 3.141 * 1.5) }
let ys2 = Array(1..<10).map { x in return cos(Double(x) / 2.0 / 3.141) }
let yse1 = ys1.enumerate().map { x, y in return ChartDataEntry(x: Double(x), y: y) }
let yse2 = ys2.enumerate().map { x, y in return ChartDataEntry(x: Double(x), y: y) }
let data = LineChartData()
let ds1 = LineChartDataSet(values: yse1, label: "Hello")
ds1.colors = [NSUIColor.redColor()]
data.addDataSet(ds1)
let ds2 = LineChartDataSet(values: yse2, label: "World")
ds2.colors = [NSUIColor.blueColor()]
data.addDataSet(ds2)
lineChartView.data = data
lineChartView.gridBackgroundColor = NSUIColor.whiteColor()
lineChartView.descriptionText = "Linechart Demo"
lineChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .Linear)
lineChartView.translatesAutoresizingMaskIntoConstraints = true
self.view.addSubview(lineChartView)
let horizontalConstraint = NSLayoutConstraint(item: inspectorView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 20)
self.view.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: inspectorView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: titleLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10)
self.view.addConstraint(verticalConstraint)
self.view.addConstraint(NSLayoutConstraint(item: inspectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10))
Whenever lineChartView.translatesAutoresizingMaskIntoConstraints is false the chart is not drawn. If I set it to true the chart is drawn but the runtime says it could not satisfy all constraints.
I also do the same with a standard NSButton for which .translatesAutoresizingMaskIntoConstraints = false works as expected
Why isn't it working for LineChartView and what needs to be changed?
UPDATE: as was pointed out in the comments: Adding height and width constraints solved the problem

Swift : Adding Constraints to UILabel Programmatically

So I had a break from iOS dev for 4 months and its seems I have forgotten everything. All I am trying to do is place a Label programmatically at 0,0, size 200,50. I hear there is a few changes in iOS8 which I don't remember
let x : CGFloat = 0.0
let y : CGFloat = 0.0
let width : CGFloat = 200.0
let height : CGFloat = 50.0
self.label = UILabel(frame: CGRect(x: x, y: y, width: width, height: height))
self.label.text = "SIMON"
self.label.textColor = UIColor.whiteColor()
self.label.font = UIFont(name: "HelveticaNeue-UltraLight", size: 24)
self.label.textAlignment = NSTextAlignment.Center
self.label.backgroundColor = UIColor.redColor()
self.label.layer.masksToBounds = true;
self.label.layer.cornerRadius = 8.0;
self.label.adjustsFontSizeToFitWidth = true;
self.label.translatesAutoresizingMaskIntoConstraints = false
widthConstraint = NSLayoutConstraint(item: self.label, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: width)
heightConstraint = NSLayoutConstraint(item: self.label, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: height)
leftConstraint = NSLayoutConstraint(item: self.label, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1, constant: x)
topConstraint = NSLayoutConstraint(item: self.label, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.TopMargin, multiplier: 1, constant: y)
self.view.addSubview(self.label)
NSLayoutConstraint.activateConstraints([leftConstraint,topConstraint, widthConstraint, heightConstraint] )
It appears I was being dump!
It was the event I was calling it from, not the code. Moved to viewWillAppear

Generate labels and align in middle

How can i generate a random amount of labels and align them next to each other in the middle?
I have this code to generate an label:
var label = UILabel(frame: CGRectMake(5, 196, 35,45 ))
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.redColor()
label.text = "1";
label.tag = 5;
self.view.addSubview(label);
This work perfect, but how can i generate more than 1 label and set them next to each other in the middle?
like this:
The green things are my labels, and are align horizontally. How can i do this programmatically?
This will do it:
var lastLabel : UILabel?
var count = 1
#IBAction func addlabel(sender: AnyObject) {
var label = UILabel()
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.redColor()
label.text = count.description;
count++
label.tag = 5;
var centerX = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
centerX.priority = 999
//This if you want to center it vertically also
var centerY = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
var height = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35)
var width = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 45)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(label);
if let prevlabel = lastLabel {
var align = NSLayoutConstraint(item: prevlabel, attribute: NSLayoutAttribute.TrailingMargin, relatedBy: NSLayoutRelation.Equal, toItem: label, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1, constant: -20)
//Here just add the NSLayoutConstraint you want to apply, if its only horizontal then not add centerY
NSLayoutConstraint.activateConstraints([align, centerY, height, width, centerX])
}else {
NSLayoutConstraint.activateConstraints([centerX, centerY, height, width])
}
lastLabel = label
}

Horizontal Align labels [duplicate]

This question already has an answer here:
Generate labels and align in middle
(1 answer)
Closed 7 years ago.
How can i generate a random amount of labels and align them next to each other in the middle?
I have this code to generate an label:
var label = UILabel(frame: CGRectMake(5, 196, 35,45 ))
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.redColor()
label.text = "1";
label.tag = 5;
self.view.addSubview(label);
This work perfect, but how can i generate more than 1 label and set them next to each other in the middle?
like this:
Or if i generate 3 labels it must looks like this:
Is this possible to do it programmaticly?
This will do it:
var lastLabel : UILabel?
var count = 1
#IBAction func addlabel(sender: AnyObject) {
var label = UILabel()
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.redColor()
label.text = count.description;
count++
label.tag = 5;
var centerX = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
centerX.priority = 999
//This if you want to center it vertically also
var centerY = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
var height = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35)
var width = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 45)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(label);
if let prevlabel = lastLabel {
var align = NSLayoutConstraint(item: prevlabel, attribute: NSLayoutAttribute.TrailingMargin, relatedBy: NSLayoutRelation.Equal, toItem: label, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1, constant: -20)
//Here just add the NSLayoutConstraint you want to apply, if its only horizontal then not add centerY
NSLayoutConstraint.activateConstraints([align, centerY, height, width, centerX])
}else {
NSLayoutConstraint.activateConstraints([centerX, centerY, height, width])
}
lastLabel = label
}