Swift textViewDidBeginEditing and textViewDidEndEditing Not Working - ios

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

Related

How do I change what is shown when the UISegmentedControl index is changed?

I have a small issue with my segmented controller and trying to change the views shown to the user when clicking a new index. I have code set to show text-boxes that the user would type into when the index is changed. One issue is that I want to place text-boxes under the segmented controller evenly and the other issue is that when I click a new index in the controller, the prior text box is still on the screen, but I need it to show just the text box correlating to the specific index that is chosen. The code is shown below where I created the segment controller and handled the switch of indexes as well as the creation of the text-boxes.
let segmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["Inventory", "Sale", "Expense"])
sc.selectedSegmentIndex = 0
sc.layer.cornerRadius = 9
sc.layer.borderWidth = 1
sc.layer.borderColor = UIColor.lightGray.cgColor
sc.layer.masksToBounds = true
sc.addTarget(self, action: #selector(handleSegmentChange), for: .valueChanged)
return sc
}()
//function to handle click of segmented control buttons
#objc fileprivate func handleSegmentChange(sender: UISegmentedControl){
print(segmentedControl.selectedSegmentIndex)
switch segmentedControl.selectedSegmentIndex{
case 0:
view.addSubview(myProduct)
case 1:
view.addSubview(myRetail)
default:
view.addSubview(myExpense)
break
}
}
let myProduct : UITextField = {
let mp = UITextField(frame: CGRect(x: 10, y: 320, width: 300, height: 10))
mp.placeholder = "Enter Product name"
mp.borderStyle = UITextField.BorderStyle.line
mp.backgroundColor = .white
mp.textColor = .cyan
return mp
}();
let myRetail : UITextField = {
let mp = UITextField(frame: CGRect(x: 10, y: 320, width: 300, height: 20))
mp.placeholder = "Enter Retail price"
mp.borderStyle = UITextField.BorderStyle.line
mp.backgroundColor = .white
mp.textColor = .cyan
return mp
}();
let myExpense : UITextField = {
let mp = UITextField(frame: CGRect(x: 10, y: 320, width: 300, height: 30))
mp.placeholder = "Enter Expense name"
mp.borderStyle = UITextField.BorderStyle.line
mp.backgroundColor = .white
mp.textColor = .cyan
return mp
}();
Most of the solutions I have seen are outdated, which is why I am posting my own version here. Thanks in advance for help anyone can provide.
You can set tag for each UITextField as below,
let myProduct : UITextField = {
let mp = UITextField(frame: CGRect(x: 10, y: 320, width: 300, height: 10))
mp.placeholder = "Enter Product name"
mp.borderStyle = UITextField.BorderStyle.line
mp.backgroundColor = .white
mp.textColor = .cyan
mp.tag = 11
return mp
}()
let myRetail : UITextField = {
let mp = UITextField(frame: CGRect(x: 10, y: 320, width: 300, height: 20))
mp.placeholder = "Enter Retail price"
mp.borderStyle = UITextField.BorderStyle.line
mp.backgroundColor = .white
mp.textColor = .cyan
mp.tag = 12
return mp
}()
let myExpense : UITextField = {
let mp = UITextField(frame: CGRect(x: 10, y: 320, width: 300, height: 30))
mp.placeholder = "Enter Expense name"
mp.borderStyle = UITextField.BorderStyle.line
mp.backgroundColor = .white
mp.textColor = .cyan
mp.tag = 13
return mp
}()
and then inside handleSegmentChange, remove any view with that tag before adding a new one as below,
//function to handle click of segmented control buttons
#objc fileprivate func handleSegmentChange(sender: UISegmentedControl){
print(segmentedControl.selectedSegmentIndex)
[11, 12, 13].forEach { self.view.viewWithTag($0)?.removeFromSuperview() }
switch segmentedControl.selectedSegmentIndex {
case 0:
view.addSubview(myProduct)
case 1:
view.addSubview(myRetail)
default:
view.addSubview(myExpense)
}
}
For the position issue, you haven't set any frame to UISegmentControl. You can set frame as below to get the result shown,
let segmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["Inventory", "Sale", "Expense"])
sc.selectedSegmentIndex = 0
sc.layer.cornerRadius = 9
sc.layer.borderWidth = 1
sc.layer.borderColor = UIColor.lightGray.cgColor
sc.layer.masksToBounds = true
sc.frame = CGRect(origin: CGPoint(x: 10, y: 280), size: CGSize(width: 300, height: 30))
sc.addTarget(self, action: #selector(handleSegmentChange), for: .valueChanged)
return sc
}()

Add UILabel on random position on UIView

How do I Achieve Something like below image,
I want to add n number of UILabel to screen on random position without overlapping of label, and also randomly set rotate.
Here is my code, but it is overlapping label to another label:
override func viewDidLoad() {
super.viewDidLoad()
var textDatas = ["aaa","bbb","cccccc","ddddddd","ee","ffffff","ggggg","hhhh","iiiiii","jjjjjj","kkkkkk","ll","mmmmm","nnnnnnnn","ooooooooo","ppppppppp","qqqqqqqqqqqq","rrrrrrrr","sssssss","ttttttttt","uuuuuuu","vvvv","wwww","xxxxxx","yyyy","zzzzzzz"]
textDatas.forEach { (textData) in
let randomIntX = Int.random(in: 10..<Int(ScreenSize.SCREEN_WIDTH-200))
let randomIntY = Int.random(in: 50..<Int(ScreenSize.SCREEN_HEIGHT-50))
let randomIntFontSize = Int.random(in: 10..<40)
let randomIntLabelRotate = Int.random(in: 1..<3)
let label = UILabel(frame: CGRect(x: randomIntX, y: randomIntY, width: 200, height: 30))
label.font = UIFont(name: FONT_AVENIR_HEAVY,
size: CGFloat(randomIntFontSize))
label.textColor = .white
label.textAlignment = .center
label.text = textData
label.sizeToFit()
if randomIntLabelRotate == 1 {
label.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
}
self.view.addSubview(label)
}
}
Is there any library or solution of this will be very appreciated. Thanks

Why the image is not changed when to hit the text field of Login Id and Password?

Why is the image not changed when to hit the text field with Login Id and Password? I am a newbie to iOS, I don't know what's the issue with this code. When I want to hit the LogID and Password field then icons are not changed. Can somebody please tell me how to solve this issue.
UITextField (Extension)
class TextField
{
static func imgTFEmail1(tfLgnID: UITextField)
{
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad
{
//Set image within username textfield
tfLgnID.leftViewMode = .always
imgViewLgn = UIImageView(frame: CGRect(x: tfLgnID.frame.origin.x + 3, y: tfLgnID.frame.origin.y + 20, width: 35, height: 30))
imgViewLgn.contentMode = .scaleAspectFit
imgLogin = UIImage(named: "user1")!
imgViewLgn.image = imgLogin
tfLgnID.leftView = imgViewLgn
//Text and Placeholder Font Size Large
let attributes = [
NSAttributedStringKey.foregroundColor: UIColor.lightGray,
NSAttributedStringKey.font : UIFont(name: "Avenir-Heavy", size: 25)!
]
tfLgnID.attributedPlaceholder = NSAttributedString.init(string: "Login Id", attributes: attributes)
//Label Detail increase the font weight and family
tfLgnID.font = UIFont(name: "Avenir-Heavy", size: 28)
}
else if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.phone
{
//Set image within username textfield
tfLgnID.leftViewMode = .always
imgViewLgn = UIImageView(frame: CGRect(x: -5, y: 0, width: 25, height: 22))
imgViewLgn.contentMode = .scaleAspectFit
imgLogin = UIImage(named: "user1")!
imgViewLgn.image = imgLogin
tfLgnID.leftView = imgViewLgn
}
}
static func imgTFPwd1(tfPwd: UITextField)
{
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad
{
//Set image within password textfield
tfPwd.leftViewMode = .always
imgViewPwd = UIImageView(frame: CGRect(x: tfPwd.frame.origin.x + 3, y: tfPwd.frame.origin.y + 20, width: 35, height: 30))
imgViewPwd.contentMode = .scaleAspectFit
imgPwd = UIImage(named: "password1")!
imgViewPwd.image = imgPwd
tfPwd.leftView = imgViewPwd
//Text and Placeholder Font Size Large
let attributes = [
NSAttributedStringKey.foregroundColor: UIColor.lightGray,
NSAttributedStringKey.font : UIFont(name: "Avenir-Heavy", size: 25)!
]
tfPwd.attributedPlaceholder = NSAttributedString.init(string: "Password", attributes: attributes)
//Label Detail increase the font weight and family
tfPwd.font = UIFont(name: "Avenir-Heavy", size: 28)
}
else if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.phone
{
//Set image within password textfield
tfPwd.leftViewMode = .always
imgViewPwd = UIImageView(frame: CGRect(x: -5, y: 0, width: 25, height: 22))
imgViewPwd.contentMode = .scaleAspectFit
imgPwd = UIImage(named: "password1")!
imgViewPwd.image = imgPwd
tfPwd.leftView = imgViewPwd
}
}
ViewController
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
//Show the horizontal line in the bottom of text fields
self.designTextField()
TextField.imgTFEmail1(tfLgnID: tfLgnID)
TextField.imgTFPwd1(tfPwd: tfPwd)
}
func textFieldDidBeginEditing(_ textField: UITextField)
{
//Move the screen up when tap on TextField
self.view.frame.origin.y -= 80
if textField == self.tfLgnID
{
bottomTFEmail.backgroundColor = UIColor(red: 11/255, green: 174/255, blue: 250/255, alpha: 1).cgColor
TextField.imgTFEmail2(tfLgnID: tfLgnID)
TextField.imgTFPwd2(tfPwd: tfPwd)
}
else if textField == self.tfPwd
{
imgPwd = UIImage(named: "password2")!
bottomTFPwd.backgroundColor = UIColor(red: 11/255, green: 174/255, blue: 250/255, alpha: 1).cgColor
}
}
func textFieldDidEndEditing(_ textField: UITextField)
{
self.view.frame.origin.y = 0
if textField == self.tfLgnID
{
bottomTFEmail.backgroundColor = UIColor.lightGray.cgColor
imgLogin = UIImage(named: "user1")!
imgViewLgn.image = imgLogin
tfLgnID.leftView = imgViewLgn
if !(Utility.validateEmail(candidate: self.tfLgnID.text!))
{
let alertController = UIAlertController.alertCtrl(title: "Warning", message: "Please enter your correct email address", buttonTitle: "OK")
self.present(alertController, animated: true, completion: nil)
}
}
else if textField == self.tfPwd
{
bottomTFPwd.backgroundColor = UIColor.lightGray.cgColor
imgPwd = UIImage(named: "password1")!
imgViewPwd.image = imgPwd
tfPwd.leftView = imgViewPwd
}
}
Results
Without Hitting
When Hitting

how to print text from textField in label programmatically swift

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

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