how to print text from textField in label programmatically swift - ios

i like to print textField Value in label by clicking button key. but i have been unable to do it. below is codes
import UIKit
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.gray
setupLabel()
setupTextField()
setupButton()
}
func setupLabel() {
let label = UILabel()
label.frame = CGRect(x: 40, y: 80, width: 300, height: 60)
label.text = "welcome to my world"
label.textColor = UIColor.yellow
label.font = UIFont.boldSystemFont(ofSize: 25)
label.textAlignment = .center
label.layer.borderWidth = 2
label.layer.borderColor = UIColor.yellow.cgColor
label.layer.cornerRadius = 5
view.addSubview(label)
}
func setupTextField() {
let textField = UITextField()
textField.frame = CGRect(x: 10, y: 200, width: self.view.frame.size.width - 20, height: 60)
textField.placeholder = "text here"
textField.textAlignment = .center
textField.font = UIFont.systemFont(ofSize: 25)
textField.layer.borderWidth = 2
textField.layer.borderColor = UIColor.yellow.cgColor
textField.layer.cornerRadius = 5
view.addSubview(textField)
}
func setupButton() {
let button = UIButton()
button.frame = CGRect(x: 50, y: 300, width: self.view.frame.size.width - 100, height: 60)
button.setTitle("Enter", for: .normal)
button.setTitleColor(UIColor.yellow, for: .normal)
button.layer.borderWidth = 2
button.layer.borderColor = UIColor.yellow.cgColor
button.layer.cornerRadius = 5
button.addTarget(self, action: #selector(buttonTarget), for: .touchUpInside)
view.addSubview(button)
}
func buttonTarget() {
// i missed of here
}
}

in here you need to follow two steps
you need to create the label and textfield in globally not instance, for e.g
class MainViewController: UIViewController
let label = UILabel()
let textField = UITextField()
hide the instance vale of your allocation
func setupLabel() {
//let label = UILabel()
label.frame = CGRect(x: 40, y: 80, width: 300, height: 60)
label.text = "welcome to my world"
label.textColor = UIColor.yellow
label.font = UIFont.boldSystemFont(ofSize: 25)
label.textAlignment = .center
label.layer.borderWidth = 2
label.layer.borderColor = UIColor.yellow.cgColor
label.layer.cornerRadius = 5
view.addSubview(label)
}
then you can access the value directly anywhere in your class
func buttonTarget() {
if let text = textField.text
{
label.text = text
}
}

Related

how to send a text with a send button to text field on swift iOS

I really new. all I want to do is send in the text I got on the password field as a secure text to the text field if that's possible. kind of like sending a text but with the secure text. the secure button just lets you see what is inside. I got that to work but I don't know how to transfer the information from one place to the other. do I create a function? Im sorry im a complete noob.
import UIKit
class ViewController: UIViewController {
private let scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.clipsToBounds = true
return scrollView
}()
private let secureButton : UIButton = {
let button = UIButton()
button.setTitle("Secure", for: .normal)
button.backgroundColor = .link
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 12
button.titleLabel?.font = .systemFont(ofSize: 20, weight: .bold)
button.layer.masksToBounds = true
button.addTarget( self, action: #selector(securebuttonTapped), for: .touchUpInside)
return button
}()
let sendButton : UIButton = {
let button = UIButton()
button.setTitle("Send", for: .normal)
button.backgroundColor = .green
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 12
button.titleLabel?.font = .systemFont(ofSize: 20, weight: .bold)
button.layer.masksToBounds = true
button.addTarget( self, action: #selector(sendButtonTapped), for: .touchUpInside)
return button
}()
let textView = UITextView()
private let passwordField: UITextField = {
let field = UITextField()
field.autocapitalizationType = .none
field.autocorrectionType = .no
field.returnKeyType = .done
field.layer.cornerRadius = 12
field.layer.borderWidth = 1
field.layer.borderColor = UIColor.lightGray.cgColor
field.placeholder = "Password"
field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 0))
field.leftViewMode = .always
field.backgroundColor = .white
field.isSecureTextEntry = true
return field
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .gray
view.addSubview(scrollView)
scrollView.addSubview(passwordField)
scrollView.addSubview(secureButton)
scrollView.addSubview(textView)
scrollView.addSubview(sendButton)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
passwordField.frame = CGRect(x: 30,
y: 100,
width: scrollView.width-60,
height: 52)
secureButton.frame = CGRect(x: 30,
y: passwordField.bottom+10 ,
width: scrollView.width-60,
height: 30)
textView.frame = CGRect(x: 30,
y: secureButton.bottom+10 ,
width: scrollView.width-60,
height: 30)
sendButton.frame = CGRect(x: 30,
y: textView.bottom+10 ,
width: scrollView.width-60,
height: 30)
}
#objc func securebuttonTapped() {
let text = passwordField
text.isSecureTextEntry = !text.isSecureTextEntry
}
#objc func sendButtonTapped() {
let text = passwordField
textView.inputView = text
print("send button tapped")
}
}
Swift 5
if you want to pass the data in the same controller its very simple. just asign the text to the textField on button Pressed
var textField = UITexField()
#objc func sendButtonTapped() {
// here you will assign the text you got from the password field to watever textfield you want, whether it is secure text or simple text.
textField.text = passwordField.text
print("send button tapped")
}
if you want to pass that text to some other ViewController you need to send like this
let vc = UIStoryboard(name: "Main", bundle:
nil).instantiateViewController(withIdentifier: "YourViewController") as!
YourViewController
// here you will assign the text to the variable from other viewcontroller you
want to.
vc.text = "Enter the text here"
self.navigationController?.pushViewController(vc, animated: true)

Swift textViewDidBeginEditing and textViewDidEndEditing Not Working

I'm trying to get my UITextView feedbackInput to delete the placeholder text when it's clicked inside of and then let the user type in the UITextView in a black font color. Also if the user clicks inside of the UITextView, but doesn't type anything and then clicks outside of it, the placeholder text should be redisplayed. Currently, my code loads the placeholder text correctly, but when the user clicks inside of the UITextView the placeholder text isn't immediately removed and the user can only type in the UITextView in the light gray placeholder text font color, not in black.
AddMeal View Code:
import SwiftUI
class AddMeal: UIViewController, UITextViewDelegate {
#State var stars = -1
var feedbackInput = UITextView(frame: CGRect(x: 20, y: 440, width: 372, height: 100))
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
// Add Meal Title Label
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
label.center = self.view.center
label.center.x = self.view.center.x
label.center.y = 75
label.font = label.font.withSize(30);
label.textAlignment = .center
label.textColor = .white
label.text = "Add Meal"
self.view.addSubview(label)
// Meal Title Label
let food = UILabel(frame: CGRect(x: 22, y: 100, width: 200, height: 50))
food.font = label.font.withSize(20);
food.textColor = .white
food.text = "Meal Title"
self.view.addSubview(food)
// Food Title Input Text Field
let sampleTextField = UITextField(frame: CGRect(x: 20, y: 150, width: 372, height: 40))
sampleTextField.placeholder = "Enter the Name of the Food or Drink..."
sampleTextField.font = UIFont.systemFont(ofSize: 15)
sampleTextField.borderStyle = UITextField.BorderStyle.roundedRect
sampleTextField.autocorrectionType = UITextAutocorrectionType.no
sampleTextField.keyboardType = UIKeyboardType.default
sampleTextField.returnKeyType = UIReturnKeyType.done
sampleTextField.clearButtonMode = UITextField.ViewMode.whileEditing
sampleTextField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
self.view.addSubview(sampleTextField)
// Meal Calories Label
let mealCalories = UILabel(frame: CGRect(x: 22, y: 200, width: 200, height: 50))
mealCalories.font = label.font.withSize(20);
mealCalories.textColor = .white
mealCalories.text = "Meal Calories"
self.view.addSubview(mealCalories)
// Calories Input Text Field
let sampleTextField2 = UITextField(frame: CGRect(x: 20, y: 250, width: 372, height: 40))
sampleTextField2.placeholder = "Enter the # of Calories..."
sampleTextField2.font = UIFont.systemFont(ofSize: 15)
sampleTextField2.borderStyle = UITextField.BorderStyle.roundedRect
sampleTextField2.autocorrectionType = UITextAutocorrectionType.no
sampleTextField2.keyboardType = UIKeyboardType.default
sampleTextField2.returnKeyType = UIReturnKeyType.done
sampleTextField2.clearButtonMode = UITextField.ViewMode.whileEditing
sampleTextField2.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
self.view.addSubview(sampleTextField2)
// Meal Rating Label
let mealRating = UILabel(frame: CGRect(x: 22, y: 300, width: 200, height: 50))
mealRating.font = label.font.withSize(20);
mealRating.textColor = .white
mealRating.text = "Meal Rating"
self.view.addSubview(mealRating)
// Rating Stars
let stars = UIHostingController(rootView: StarsView())
self.view.addSubview(stars.view)
self.addChild(stars)
stars.view.backgroundColor = .clear
stars.view.translatesAutoresizingMaskIntoConstraints = false
stars.view.sizeToFit()
stars.view.topAnchor.constraint(equalTo: mealRating.bottomAnchor, constant: 5).isActive = true
stars.view.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
// Meal Feedback Label
let mealFeedback = UILabel(frame: CGRect(x: 22, y: 390, width: 200, height: 50))
mealFeedback.font = label.font.withSize(20);
mealFeedback.textColor = .white
mealFeedback.text = "Meal Feedback"
self.view.addSubview(mealFeedback)
// Feedback Input Field
feedbackInput.delegate = self
feedbackInput.text = "Enter Your Feedback on the Meal..."
feedbackInput.layer.cornerRadius = 5
feedbackInput.font = UIFont.systemFont(ofSize: 15)
feedbackInput.textColor = .lightGray
self.view.addSubview(feedbackInput)
}
}
func textViewDidBeginEditing(textView: UITextView) {
if textView.textColor == .lightGray {
textView.text = ""
textView.textColor = .black
}
}
func textViewDidEndEditing(textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Enter Your Feedback on the Meal..."
textView.textColor = .lightGray
}
}
struct StarsView: View {
#State var stars = -1
var body: some View {
HStack {
ForEach(0..<5){ i in
Image(systemName: "star.fill")
.resizable().frame(width: 30, height:30)
.foregroundColor(self.stars >= i ? .yellow : .gray)
.onTapGesture {
self.stars = i
}
}
}
}
}
Image of Current Output:
How can I fix the issue of textViewDidBeginEditing and textViewDidEndEditing not being called correctly for my UITextView feedbackInput to work properly as I described above?
You need to set placeholder, not text.
override func viewDidLoad() {
super.viewDidLoad()
...
mealFeedback.placeholder = "Meal Feedback"
feedbackInput.placeholder = "Enter Your Feedback on the Meal..."
}
func textViewDidBeginEditing(textView: UITextView) {
if textView.textColor == .lightGray {
textView.placeholder = ""
textView.textColor = .black
}
}
func textViewDidEndEditing(textView: UITextView) {
if textView.text.isEmpty {
textView.placeholder = "Enter Your Feedback on the Meal..."
textView.textColor = .lightGray
}
}
Your delegate callbacks are outside of your view controller context, but must be inside
class AddMeal: UIViewController, UITextViewDelegate {
// #State var stars = -1 // << !! BTW, don't use state here - it will not work
// ... other code
func textViewDidBeginEditing(textView: UITextView) {
if textView.textColor == .lightGray {
textView.text = ""
textView.textColor = .black
}
}
func textViewDidEndEditing(textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Enter Your Feedback on the Meal..."
textView.textColor = .lightGray
}
}
}

Swift 3: How do I increase a variable being displayed as a UILabel, and then update the UILabel programmatically?

I have a label that is supposed to display a score, and a button that is supposed to increase that score each time it's pressed. My problem is that I get an error no matter where I put my function.
If I have the function above the viewDidLoad class then I get an error because it comes before my label, but if I put it anywhere inside viewDidLoad I get an error because I can't call a local function, and if I put it anywhere after, then my button calling the function comes before the function.
Where am I supposed to put these things? Is there a better way of doing this all together? This was supposed to be so simple...
import UIKit
class ViewController: UIViewController {
let phrase = "Your score: "
var increasingNum = 0
func scoreGoUp (sender: UIButton){
increasingNum += 1
label.text = "\(phrase) \(increasingNum)"
}
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: self.view.frame.size.width / 2 - 100, y: self.view.frame.size.height / 2 - 10, width: 200, height: 20))
label.textAlignment = .center
label.text = "\(phrase) \(increasingNum)"
self.view.addSubview(label)
let button = UIButton(frame: CGRect(x: self.view.frame.size.width / 2 - 150, y: 100, width: 300, height: 50))
button.backgroundColor = UIColor.cyan
button.addTarget(self, action: #selector(scoreGoUp), for: .touchUpInside)
self.view.addSubview(button)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
I have modified your code. Hope this help you.
class ViewController: UIViewController {
var label:UILabel!
let phrase = "Your score: "
var increasingNum = 0
override func viewDidLoad() {
super.viewDidLoad()
label = UILabel(frame: CGRect(x: self.view.frame.size.width / 2 - 100, y: self.view.frame.size.height / 2 - 10, width: 200, height: 20))
label.textAlignment = .center
label.text = "\(phrase) \(increasingNum)"
self.view.addSubview(label)
let button = UIButton(frame: CGRect(x: self.view.frame.size.width / 2 - 150, y: 100, width: 300, height: 50))
button.backgroundColor = UIColor.cyan
button.addTarget(self, action: #selector(scoreGoUp), for: .touchUpInside)
self.view.addSubview(button)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func scoreGoUp (sender: UIButton){
increasingNum += 1
label.text = "\(phrase) \(increasingNum)"
}
}
Here is the output
You need to define your label outside of viewDidLoad (like increasingNum), at the moment, your label variable is only visible inside viewDidLoad
var label:UILabel!
I have cleared up your code. The problem was that, you are not keeping track of you UILabel. Just declare a label to be visible in the class.
import UIKit
class ViewController: UIViewController {
let phrase = "Your score: "
var increasingNum = 0
var label: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: self.view.frame.size.width / 2 - 100, y: self.view.frame.size.height / 2 - 10, width: 200, height: 20))
label.textAlignment = .center
label.text = "\(phrase) \(increasingNum)"
self.view.addSubview(label)
self.label = label
let button = UIButton(frame: CGRect(x: self.view.frame.size.width / 2 - 150, y: 100, width: 300, height: 50))
button.backgroundColor = UIColor.cyan
button.addTarget(self, action: #selector(scoreGoUp), for: .touchUpInside)
self.view.addSubview(button)
}
func scoreGoUp (sender: UIButton){
increasingNum += 1
self.label?.text = "\(phrase) \(increasingNum)"
}
}
Hope this helps!

Swift - UITextField Programmatically Cannot enter text

I'm new to Swift programming, I'm trying to build an app with UITextField in it, But I'm having a problem, I created an UITextField programmatically but it seems like I cannot enter a text in it. Here's my viewDidLoad
Code:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView = UITableView(frame: self.tableView.frame, style: .Grouped)
self.groupInfoView.frame = CGRectMake(0, 44, self.view.frame.width, 100)
self.groupInfoView.backgroundColor = UIColor.orangeColor()
self.groupInfoView.userInteractionEnabled = true
groupImg.frame = CGRectMake(10, 50, 40, 40)
groupImg.layer.cornerRadius = 5
groupImg.layer.masksToBounds = true
groupImg.image = UIImage(named: "group-def-img")
groupTitle = UITextField.init(frame:CGRectMake(groupImg.frame.maxX + 5, 50, self.groupInfoView.frame.width-65, 40))
groupTitle.backgroundColor = UIColor.whiteColor()
groupTitle.layer.cornerRadius = 5
groupTitle.layer.masksToBounds = true
groupTitle.placeholder = "Enter Group Title"
groupTitle.textColor = UIColor.orangeColor()
groupTitle.textAlignment = .Center
groupTitle.font = UIFont(name: "HelveticaNeue-Light", size: 18)
groupTitle.autocorrectionType = UITextAutocorrectionType.No
groupTitle.keyboardType = UIKeyboardType.Default
groupTitle.returnKeyType = UIReturnKeyType.Done
groupTitle.clearButtonMode = UITextFieldViewMode.WhileEditing;
groupTitle.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
groupTitle.enabled = true
groupTitle.userInteractionEnabled = true
groupTitle.delegate = self
groupTitle.text = "asda"
recipientLabel.frame = CGRectMake(5, 0, self.view.frame.width - 20, 40)
recipientLabel.font = UIFont(name: "HelveticaNeue-Light", size: 15)
recipientLabel.numberOfLines = 3
recipientLabel.textColor = UIColor.orangeColor()
recipientLabel.backgroundColor = UIColor.whiteColor()
recipientLabel.center.x = self.view.center.x
recipientLabel.layer.cornerRadius = 7
recipientLabel.layer.masksToBounds = true
recipientLabel.text = " To:"
self.groupInfoView.addSubview(groupTitle)
self.groupInfoView.addSubview(recipientLabel)
self.groupInfoView.addSubview(groupImg)
searchBar.delegate = self
self.titleLabel.text = "New Group Message"
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.tabBarController?.tabBar.barStyle = .Black
self.navigationController!.navigationBar.translucent = false
self.navigationController!.navigationBar.barTintColor = UIColor.orangeColor()
tableView.separatorInset = UIEdgeInsets(top: 0, left: 65, bottom: 0, right: 0)
tableView.registerClass(UserCell.self, forCellReuseIdentifier: cellId)
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: #selector(handleCancel))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .Done, target: self, action: #selector(handleDone))
fetchUser()
self.tableView.allowsMultipleSelection = true
if let navigationBar = self.navigationController?.navigationBar {
let firstFrame = CGRectMake(0, -5, (self.navigationController?.navigationBar.frame.width)!, 40)
let secondFrame = CGRectMake(0, 17, (self.navigationController?.navigationBar.frame.width)!, 30)
titleLabel.frame = firstFrame
titleLabel.textColor = UIColor.whiteColor()
titleLabel.font = UIFont(name: "HelveticaNeue-SemiBold", size: 18)
titleLabel.textAlignment = .Center
countLabel.textColor = UIColor.whiteColor()
countLabel.font = UIFont(name: "HelveticaNeue-Light", size: 13)
countLabel.frame = secondFrame
countLabel.textAlignment = .Center
navigationBar.addSubview(groupInfoView)
navigationBar.addSubview(titleLabel)
navigationBar.addSubview(countLabel)
}
And this is my references:
Code:
var titleLabel = UILabel()
var countLabel = UILabel()
var recipientLabel = UILabel()
var groupImg = UIImageView()
var groupTitle: UITextField = UITextField()
var groupInfoView = UIView()
Declare its globally so you can access it anywhere. and declare its delegates UITextFieldDelegate Headerimageview is my heartimage and HeaderView is my simple header view.
#IBOutlet var Headerimageview: UIImageView!
#IBOutlet var HeaderView: UIView!
var groupTitle : UITextField = UITextField()
In viewDidLoad()
groupTitle = UITextField.init(frame: CGRectMake(Headerimageview.frame.size.width + 25, 5, self.view.frame.width-85, 40))
groupTitle.backgroundColor = UIColor.whiteColor()
groupTitle.layer.cornerRadius = 5
groupTitle.layer.borderWidth = 1.0
groupTitle.layer.borderColor = UIColor.brownColor().CGColor
groupTitle.layer.masksToBounds = true
groupTitle.placeholder = "Enter Group Title"
groupTitle.textColor = UIColor.orangeColor()
groupTitle.textAlignment = .Center
groupTitle.font = UIFont(name: "HelveticaNeue-Light", size: 18)
groupTitle.autocorrectionType = UITextAutocorrectionType.No
groupTitle.keyboardType = UIKeyboardType.Default
groupTitle.returnKeyType = UIReturnKeyType.Done
groupTitle.clearButtonMode = UITextFieldViewMode.WhileEditing
groupTitle.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
groupTitle.enabled = true
groupTitle.userInteractionEnabled = true
groupTitle.delegate = self
self.HeaderView.addSubview(groupTitle)
Output :
TextField should begin editing method called
TextField did begin editing method called
While entering the characters this method gets called
While entering the characters this method gets called
While entering the characters this method gets called
TextField should return method called
TextField should snd editing method called
TextField did end editing method called
Update your this code with mine one...
groupTitle = UITextField.init(frame:CGRectMake(groupImg.frame.maxX + 5, 25, self.groupInfoView.frame.width-65, 40))
groupTitle = UITextField.init(frame: CGRectMake(groupImg.frame.size.width + 25, 25, self.view.frame.width-85, 40))
self.groupInfoView.addSubview(groupTitle)
self.groupInfoView.addSubview(groupImg)
self.view.addSubview(groupInfoView)

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