Swift & UILabel : How to add padding and margin in Swift programmatically? [duplicate] - ios

This question already has answers here:
Add padding between label and its border
(4 answers)
Closed 8 months ago.
I have created a text programmatically with a grey background using UILabel.
Now I would like to add padding to this paragraph/text. Also, it would be great if you could show me how to add margin to my UILabel as well.
import UIKit
final class SignUpViewController: UIViewController {
public let identifier = "Sign Up"
private let logoImage : UIImageView = {
let imageView = UIImageView()
imageView.layer.masksToBounds = true
imageView.contentMode = .scaleAspectFit
imageView.image = UIImage(named: "MyLogoWithTitle")
imageView.clipsToBounds = true
return imageView
}()
private let instructionText : UILabel = {
let label = UILabel()
label.text = "Please read terms and conditions below carefully before proceeding with the registration."
label.backgroundColor = UIColor().colorFromHex(hex: "#2C333C", opacity: 0.4)
label.numberOfLines = 0
label.tintColor = .white
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(logoImage)
view.addSubview(instructionText)
view.backgroundColor = UIColor().colorFromHex(hex: "#141920", opacity: 1.0)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
logoImage.frame = CGRect(x: 0,
y: 0,
width: 140,
height: 60)
logoImage.center = CGPoint(x: view.center.x, y: view.height/5)
instructionText.frame = CGRect(
x: 5,
y: 5 + logoImage.bottom,
width: view.width - 20,
height: 50)
.integral
instructionText.layer.cornerRadius = 10
}
}
Notice that I created an extension to UIColor so that I can input hex color in this way - UIColor().colorFromHex(hex: "#2C333C", opacity: 0.4) .
I am looking forward to hearing from you. Thank you.

You can insert this UILabel into the container (any UIView) and set its position inside.
But the simplest trick is to use UIButton instead of UILabel. You can configure UIEdgeInsets for padding.
So that UIButton does not act as a button simply set button.isUserInteractionEnabled = false.
By default, text in the button are placed in the center, but its position is easy to change with contentHorizontalAlignment and contentVerticalAlignment
And as a bonus, you can add icons right near to the text. :)
UPD.
Could you give me a simple example? I tried that way but I didn't get the result I expected. – Punreach Rany
let buttonUsedAsLabel = UIButton()
// Your question was about padding
// It's it!
buttonUsedAsLabel.titleEdgeInsets = UIEdgeInsets(top: 5, left: 20, bottom: 5, right: 20)
// Make it not user interactable as UILabel is
buttonUsedAsLabel.isUserInteractionEnabled = false
// set any other properties
buttonUsedAsLabel.setTitleColor(.white, for: .normal)
buttonUsedAsLabel.contentVerticalAlignment = .top
buttonUsedAsLabel.contentHorizontalAlignment = .left
// Set title propeties AFTER it was created with text because it's nullable
// You can use attributed title also
// Never use any (button.titleLabel) before its creation
// for example: (button.titleLabel?.text = "zzz") do nothing here
buttonUsedAsLabel.setTitle("This is the text", for: .normal)
buttonUsedAsLabel.titleLabel?.font = .systemFont(ofSize: 20, weight: .medium)
buttonUsedAsLabel.titleLabel?.numberOfLines = 0
buttonUsedAsLabel.titleLabel?.lineBreakMode = .byWordWrapping
// and so on
// ...
// This is the triсk :)
Of course, you can do it with a storyboard if prefer.

1. Add this class
PaddingLabel.swift
import UIKit
class PaddingLabel: UILabel {
var edgeInset: UIEdgeInsets = .zero
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: edgeInset.top, left: edgeInset.left, bottom: edgeInset.bottom, right: edgeInset.right)
super.drawText(in: rect.inset(by: insets))
}
override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + edgeInset.left + edgeInset.right, height: size.height + edgeInset.top + edgeInset.bottom)
}
}
2. Add this code to your ViewController
let label = PaddingLabel()
override func viewDidLoad() {
super.viewDidLoad()
label.backgroundColor = UIColor().colorFromHex(hex: "#2C333C", opacity: 0.4)
//Setting the padding label
label.edgeInset = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
}
The answer to the link below is that I wrote the same content based on the storyboard.
Add padding between label and its border

I use textfield. Set padding and text in textfield. And do not allow editing.
extension UITextField {
func addLeftPadding() {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 12, height: self.frame.height))
self.leftView = paddingView
self.leftViewMode = ViewMode.always
}
}
//ViewController
#IBOutlet weak var myTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
myTextField.addLeftPadding()
myTextField.isUserInteractionEnabled = false
myTextField.text = "your label text"
}

Related

UITextView removing interim blank lines on resize

I have a UITextView that can potentially change size. Scrolling is disabled. Here what's happening:
Is there any way to prevent this strange behaviour but also keep the lineBreakMode to .byTruncatingTail? (removing this option produces the expected resize result)
The playground code so you can reproduce this easily:
import UIKit
import PlaygroundSupport
class HostController: UIViewController {
let textView = UITextView()
override func viewDidLoad() {
view.backgroundColor = .gray
textView.frame = CGRect(x: 10, y: 10, width: 150, height: 200)
textView.isEditable = false
textView.isScrollEnabled = false
textView.textContainer.lineBreakMode = .byTruncatingTail
textView.text = "Line 1\n\n\n\nLine 2\n\nLine 3\n\nLine 4\nSome text that goes beyond the width"
view.addSubview(textView)
let slider = UISlider(frame: CGRect(x: 160, y: 10, width: 100, height: 30))
slider.minimumValue = 10
slider.maximumValue = 200
slider.value = 200
slider.addTarget(self, action: #selector(sliderChanged(sender:)), for: .valueChanged)
view.addSubview(slider)
}
#objc func sliderChanged(sender: UISlider) {
textView.frame.size.height = CGFloat(sender.value)
}
}
let vc = HostController()
PlaygroundPage.current.liveView = vc
Turns out that if you add an empty space character between the new lines the problem is disappearing. For the example above, that would be:
textView.text = "Line 1\n \n \n \nLine 2\n \nLine 3\n \nLine 4\nSome text that goes beyond the width"

Setting height of UiLabel inside UiStackview Using swift

I am dynamically adding views in the UiStackview. Since UiStackview is not a regular view, SO I can not add a bottom border to it. That is why I have planned to add a UILabel at the end of it
The label that I will add at the end of my UIStackview will be dealt as a border. I was thinking to make its height as 1point. and give it a background color. And expand its height to full width of screen.
But its height is not getting controlled. Can anyone tell me what the problem is?
Here is the little code snippet
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 10, height: 1))
label.backgroundColor = UIColor.black
label.text = ""
bottomBorder.addArrangedSubview(label)
I am adding this in the end of the main stackview. it gets added in the main stackview but with the height of I think 30 point. Or may be its the default height of the UiLabel
My questions are:
How to add UiLabel or a border at the end of stackview (vertical alignment)
Is there any way that I can add border to my stackview directly? Four side border or at least bottom border?
You have 2 alternatives to achieve this:
1- put the stackview inside a UIView parentView
2- do not add UILabel directly to the UIStackView, add the UILabel to UIView then add the UIView to the UIStackView, so that you can whatever separators you want to the UIView.
Code to do that:
override func viewDidLoad()
{
super.viewDidLoad()
stackView.distribution = .fillEqually
let v1 = getViewForStackView(lblText: "lbl1")
let v2 = getViewForStackView(lblText: "lbl2")
stackView.addArrangedSubview(v1)
stackView.addArrangedSubview(v2)
}
func getViewForStackView(lblText:String)->UIView
{
let rectView = CGRect(x: 0, y: 0, width: 100, height: 100)
let view = UIView(frame: rectView)
view.backgroundColor = .green
let label = UILabel()
label.text = lblText
label.backgroundColor = .red
addFillingSubview(parentView: view, subview: label, insets: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8))
return view
}
func addFillingSubview(parentView:UIView, subview: UIView, insets: UIEdgeInsets = .zero)
{
subview.translatesAutoresizingMaskIntoConstraints = false
parentView.addSubview(subview)
let views = ["subview": subview]
let metrics = ["top": insets.top, "left": insets.left, "bottom": insets.bottom, "right": insets.right]
parentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-(left)-[subview]-(right)-|", options: [], metrics: metrics, views: views))
parentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(top)-[subview]-(bottom)-|", options: [], metrics: metrics, views: views))
}
Output:
Use this class
class BorderedStackView: UIStackView {
let borderWidth : Int = 2
let borderColor : UIColor = UIColor.darkGray;
var borderView : UIView!
required init(coder: NSCoder) {
super.init(coder: coder);
initializeSubviews();
}
required override init(frame: CGRect) {
super.init(frame: frame);
initializeSubviews();
}
func initializeSubviews() {
borderView = UIView.init();
borderView.backgroundColor = UIColor.black;
self.addSubview(borderView);
}
override func layoutSubviews() {
super.layoutSubviews();
var frame = self.bounds;
frame.origin.y = frame.size.height - CGFloat.init(borderWidth)
frame.size.height = CGFloat.init(borderWidth);
self.borderView.frame = frame;
self.bringSubview(toFront: self.borderView)
}
}
Uses:
let stackView = BorderedStackView.init(frame: CGRect.init(x: 50, y: 50, width: 200, height: 200));
stackView.axis = .vertical
stackView.borderWidth = 20;
stackView.borderColor = .red;
self.view.addSubview(stackView);
let subView1 = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 200, height: 100));
subView1.backgroundColor = UIColor.red;
stackView.addSubview(subView1);
let subView2 = UIView.init(frame: CGRect.init(x: 0, y: 100, width: 200, height: 100));
subView2.backgroundColor = UIColor.black;
stackView.addSubview(subView2);

Swift iOS - How to line up a sublayer position to match the center of button text

I have a button that is text. I added a red background subLayer and I made the backgroundLayer's width and height bigger then the button text. I tried to center the background layer to the button using:
backgroundLayer.position = button.center
It's not centering. This is what I get:
I know I can set the background color and cornerRadius on the button directly but when I do it that way the red background hugs the text:
button.backgroundColor = UIColor.red
button.layer.cornerRadius = 10
I want the redbackground to be wider and taller then the text:
backgroundLayer.frame = CGRect(x: 0, y: 0, width: buttonTextSize.width + 10, height: buttonTextSize.height + 5
I would Photoshop an example but I don't have Photshop in front of me at the moment. This is the closest I can find. This is a button from Vimeo. They aren't using text but the backgroundLayer is much wider and taller then the button image and the backgroundLayer's position is aligned with the button's midX and midY:
How do I get the position of the background subLayer to line up with the center of the button's text?
let button: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Next", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.contentHorizontalAlignment = .center
button.titleLabel?.font = UIFont.systemFont(ofSize: 23)
return button
}()
let backgroundLayer: CALayer = {
let layer = CALayer()
layer.backgroundColor = UIColor.red.cgColor
layer.cornerRadius = 10
return layer
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.lightGray
view.addSubview(button)
button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let buttonText = button.titleLabel?.text
let buttonTextSize = (buttonText! as NSString).size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 23.0)])
// I added 10 points to the backgroundLayer's width and 5 points to the backgroundLayer's height so its wider then the text
backgroundLayer.frame = CGRect(x: 0, y: 0, width: buttonTextSize.width + 10, height: buttonTextSize.height + 5)
button.layer.insertSublayer(backgroundLayer, at: 0)
backgroundLayer.position = button.center
}
Here's a button that seems to look the way you want (of course you can adjust any parameters that don't suit your sensibilities):
This button is automatically red, corner-rounded, and considerably larger than its text (even when the button is positioned using auto layout).
Here's how it was achieved through a subclass:
class MyRedButton : UIButton {
override func layoutSubviews() {
super.layoutSubviews()
self.backgroundColor = .red
self.layer.cornerRadius = 10
}
override var intrinsicContentSize: CGSize {
var sz = super.intrinsicContentSize
sz.width += 30; sz.height += 30
return sz
}
}
Matt's upvoted answer is correct.
Two things he pointed out to me in the comments that I was initially doing wrong was.
I tried to set backgroundLayer.position = button.center. This is wrong because the button's center is based on the frame's center and not it's bounds center. I should've set the backgroundLayer.position to match the center of the button's bounds
I tried to set the backgroundLayer's position to the button's center in viewWillLayoutSubviews which he said the button's bounds weren't known yet so the backgroundLayer had no information to base it on. I was supposed to add the code to viewDidLayoutSubviews
Here's the code here:
// 1. add the code to viewDidLayoutSubviews
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let text = button.titleLabel?.text
let textSize = (text! as NSString).size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 23.0)])
backgroundLayer.frame = CGRect(x: 0, y: 0, width: textSize.width + 10, height: textSize.height + 5)
button.layer.insertSublayer(backgroundLayer, at: 0)
// 2. get the buttons bound's center by accessing it's midX and midY
let buttonMidX = button.bounds.midX
let buttonMidY = button.bounds.midY
let buttonBoundsCenter = CGPoint(x: buttonMidX, y: buttonMidY)
// 3. set the backgroundLayer's postion to the buttonBoundsCenter
backgroundLayer.position = buttonBoundsCenter
}
And it works:

How to create custom view programmatically in swift having controls text field, button etc

I am trying to access the MyCustomView from another class using the following code in ViewController.swift ..
var view = MyCustomView(frame: CGRectZero)
.. in the viewDidLoad method. The problem is the view does not get initialized in the simulator.
I have already set class in storyboard for the current ViewController.
class MyCustomView: UIView {
var label: UILabel = UILabel()
var myNames = ["dipen","laxu","anis","aakash","santosh","raaa","ggdds","house"]
override init(){
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.addCustomView()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addCustomView() {
label.frame = CGRectMake(50, 10, 200, 100)
label.backgroundColor=UIColor.whiteColor()
label.textAlignment = NSTextAlignment.Center
label.text = "test label"
label.hidden=true
self.addSubview(label)
var btn: UIButton = UIButton()
btn.frame=CGRectMake(50, 120, 200, 100)
btn.backgroundColor=UIColor.redColor()
btn.setTitle("button", forState: UIControlState.Normal)
btn.addTarget(self, action: "changeLabel", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(btn)
var txtField : UITextField = UITextField()
txtField.frame = CGRectMake(50, 250, 100,50)
txtField.backgroundColor = UIColor.grayColor()
self.addSubview(txtField)
}
The CGRectZero constant is equal to a rectangle at position (0,0) with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.
But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:
customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)
Note that you also need to use addSubview otherwise your view is not added to the view hierarchy.
Swift 3 / Swift 4 Update:
let screenSize: CGRect = UIScreen.main.bounds
let myView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width - 10, height: 10))
self.view.addSubview(myView)
var customView = UIView()
#IBAction func drawView(_ sender: AnyObject) {
customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
customView.backgroundColor = UIColor.black //give color to the view
customView.center = self.view.center
self.view.addSubview(customView)
}
let viewDemo = UIView()
viewDemo.frame = CGRect(x: 50, y: 50, width: 50, height: 50)
self.view.addSubview(viewDemo)
view = MyCustomView(frame: CGRectZero)
In this line you are trying to set empty rect for your custom view. That's why you cant see your view in simulator.

How to create UILabel programmatically using Swift?

How do I create a UILabel programmatically using Swift in Xcode 6?
I have started with a new "Single View Application" in Xcode 6 and selected Swift for this project. I have my files AppDelegate.swift and ViewController.swift and I'm not sure what to do from here.
Creating a UILabel programmatically in Swift 3+:
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.center = CGPoint(x: 160, y: 285)
label.textAlignment = .center
label.text = "I'm a test label"
self.view.addSubview(label)
}
Here is the correct code for Swift 3, with comments for instructional purposes:
override func viewDidLoad()
{
super.viewDidLoad()
// CGRectMake has been deprecated - and should be let, not var
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
// you will probably want to set the font (remember to use Dynamic Type!)
label.font = UIFont.preferredFont(forTextStyle: .footnote)
// and set the text color too - remember good contrast
label.textColor = .black
// may not be necessary (e.g., if the width & height match the superview)
// if you do need to center, CGPointMake has been deprecated, so use this
label.center = CGPoint(x: 160, y: 284)
// this changed in Swift 3 (much better, no?)
label.textAlignment = .center
label.text = "I am a test label"
self.view.addSubview(label)
}
Just to add onto the already great answers, you might want to add multiple labels in your project so doing all of this (setting size, style etc) will be a pain. To solve this, you can create a separate UILabel class.
import UIKit
class MyLabel: UILabel {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeLabel()
}
override init(frame: CGRect) {
super.init(frame: frame)
initializeLabel()
}
func initializeLabel() {
self.textAlignment = .left
self.font = UIFont(name: "Halvetica", size: 17)
self.textColor = UIColor.white
}
}
To use it, do the following
import UIKit
class ViewController: UIViewController {
var myLabel: MyLabel()
override func viewDidLoad() {
super.viewDidLoad()
myLabel = MyLabel(frame: CGRect(x: self.view.frame.size.width / 2, y: self.view.frame.size.height / 2, width: 100, height: 20))
self.view.addSubView(myLabel)
}
}
Swift 4.X and Xcode 10
let lbl = UILabel(frame: CGRect(x: 10, y: 50, width: 230, height: 21))
lbl.textAlignment = .center //For center alignment
lbl.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl.textColor = .white
lbl.backgroundColor = .lightGray//If required
lbl.font = UIFont.systemFont(ofSize: 17)
//To display multiple lines in label
lbl.numberOfLines = 0 //If you want to display only 2 lines replace 0(Zero) with 2.
lbl.lineBreakMode = .byWordWrapping //Word Wrap
// OR
lbl.lineBreakMode = .byCharWrapping //Charactor Wrap
lbl.sizeToFit()//If required
yourView.addSubview(lbl)
If you have multiple labels in your class use extension to add properties.
//Label 1
let lbl1 = UILabel(frame: CGRect(x: 10, y: 50, width: 230, height: 21))
lbl1.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl1.myLabel()//Call this function from extension to all your labels
view.addSubview(lbl1)
//Label 2
let lbl2 = UILabel(frame: CGRect(x: 10, y: 150, width: 230, height: 21))
lbl2.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl2.myLabel()//Call this function from extension to all your labels
view.addSubview(lbl2)
extension UILabel {
func myLabel() {
textAlignment = .center
textColor = .white
backgroundColor = .lightGray
font = UIFont.systemFont(ofSize: 17)
numberOfLines = 0
lineBreakMode = .byCharWrapping
sizeToFit()
}
}
Create UILabel view outside viewDidLoad class and then add that view to your main view in viewDidLoad method.
lazy var myLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "This is label view."
label.font = UIFont.systemFont(ofSize: 12)
return label
}()
And then add that view in viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(myLabel)
// Set its constraint to display it on screen
myLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
myLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
You can create a label using the code below. Updated.
let yourLabel: UILabel = UILabel()
yourLabel.frame = CGRect(x: 50, y: 150, width: 200, height: 21)
yourLabel.backgroundColor = UIColor.orange
yourLabel.textColor = UIColor.black
yourLabel.textAlignment = NSTextAlignment.center
yourLabel.text = "test label"
self.view.addSubview(yourLabel)
Another answer in Swift 3:
let myLabel = UILabel()
myLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
myLabel.center = CGPoint(x: 0, y: 0)
myLabel.textAlignment = .center
myLabel.text = "myLabel!!!!!"
self.view.addSubview(myLabel)
Create label in swift 4
let label = UILabel(frame: CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: self.view.frame.size.width, height: 50))
label.textAlignment = .center
label.text = "Hello this my label"
//To set the color
label.backgroundColor = UIColor.white
label.textColor = UIColor.black
//To set the font Dynamic
label.font = UIFont(name: "Helvetica-Regular", size: 20.0)
//To set the system font
label.font = UIFont.systemFont(ofSize: 20.0)
//To display multiple lines
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping //Wrap the word of label
label.lineBreakMode = .byCharWrapping //Wrap the charactor of label
label.sizeToFit()
self.view.addSubview(label)
An alternative using a closure to separate out the code into something a bit neater using Swift 4:
class theViewController: UIViewController {
/** Create the UILabel */
var theLabel: UILabel = {
let label = UILabel()
label.lineBreakMode = .byWordWrapping
label.textColor = UIColor.white
label.textAlignment = .left
label.numberOfLines = 3
label.font = UIFont(name: "Helvetica-Bold", size: 22)
return label
}()
override func viewDidLoad() {
/** Add theLabel to the ViewControllers view */
view.addSubview(theLabel)
}
override func viewDidLayoutSubviews() {
/* Set the frame when the layout is changed */
theLabel.frame = CGRect(x: 0,
y: 0,
width: view.frame.width - 30,
height: 24)
}
}
As a note, attributes for theLabel can still be changed whenever using functions in the VC. You're just setting various defaults inside the closure and minimizing clutter in functions like viewDidLoad()
Swift 4.2 and Xcode 10. Somewhere in ViewController:
private lazy var debugInfoLabel: UILabel = {
let label = UILabel()
label.textColor = .white
label.translatesAutoresizingMaskIntoConstraints = false
yourView.addSubview(label)
NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: suggestionView.centerXAnchor),
label.centerYAnchor.constraint(equalTo: suggestionView.centerYAnchor, constant: -100),
label.widthAnchor.constraint(equalToConstant: 120),
label.heightAnchor.constraint(equalToConstant: 50)])
return label
}()
...
Using:
debugInfoLabel.text = debugInfo
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.center = CGPoint(x: 160, y: 285)
label.textAlignment = .center
label.text = "My label"
self.view.addSubview(label)
Try above code in ViewDidLoad
Swift 4.2 and Xcode 10
Initialize label before viewDidLoad.
lazy var topLeftLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "TopLeft"
return label
}()
In viewDidLoad add label to the view and apply constraints.
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(topLeftLabel)
topLeftLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
topLeftLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
}

Resources