Setting UITableView's accessory view to a UILabel - ios

I am trying to set the accessory view of a UITableView to a UILabel. I have tried looking around the Internet for an answer but could not find anything. Here is what I do:
let listCountLabel: UILabel = {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
label.text = "1"
label.layer.borderWidth = 2
label.layer.borderColor = UIColor.lightGray.cgColor
label.textColor = .lightGray
label.layer.cornerRadius = label.frame.height / 2
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont(name: "HelveticaNeue", size: 14)
label.textAlignment = .center
return label
}()
//Add to Subview
view.addSubview(listCountLabel)
cell.accessoryView = listCountLabel

There is no need to call view.addSubView(). Just call listCountLabel.sizeToFit() before inserting it into cell.accessoryView.
listCountLabel.sizeToFit()
cell.accessoryView = listCountLabel

Related

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 add a label at bottom of imageView programmatically?

i am trying to add a label at the bottom of imageView as a subview but when image changes its height or width the label is not responsive.
So i want to make a dynamic label.
add like
var lbl1 = UILabel(frame: CGRect(x: yourimageview.frame.origin.x, y: yourimageview.frame.origin.y + yourimageview.frame.size.height + 5, width: yourimageview.frame.size.width, height: asyourWish))
lbl1.textColor = UIColor.black
lbl1.frame = position
lbl1.backgroundColor = UIColor.clear
lbl1.textColor = UIColor.white
lbl1.text = "TEST"
self.view.addSubview(lbl1)
Here example of adding label to image
let picImage:UIImageView = {
let imageView = UIImageView()
let image = UIImage(named: "test")
imageView.image = image
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let durationLabel: UILabel = {
let label = UILabel()
label.text = "1:20:12"
label.font = UIFont(name:"HelveticaNeue-Bold", size: 15.0)
label.textAlignment = NSTextAlignment.right
label.numberOfLines = 1
label.textColor = UIColor.white
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func setupView(){
// I will skip part of image setup
self.picImage.addSubview(durationLabel)
durationLabel.bottomAnchor.constraint(equalTo: picImage.bottomAnchor).isActive = true
durationLabel.leftAnchor.constraint(equalTo: picImage.leftAnchor, constant: 5).isActive = true
durationLabel.rightAnchor.constraint(equalTo: picImage.rightAnchor, constant: -5).isActive = true
}
this code will add label to image that set constraint to bottom and left and right
Try this!
var label = UILabel()
label.frame = CGRect(x: imageView.bounds.origin.x, y: imageView.bounds.origin.y, width: 300, height: 45)
label.backgroundColor = UIColor.orange
label.textAlignment = .left
label.text = "This is a test label"
self.imageView.addSubview(label)

Initialize a button with a title from a Label in swift

I want to initialize a button's title from a Label. I have this code:
let smallSquare = CGSize(width: 30, height: 30)
let button = UIButton(frame: CGRect(origin: CGPointZero, size: smallSquare))
But, I do not know how I can initialize a title with my label:
let label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "I'am a test label"
Normally, I use this property to add a title with a string:
button.setTitle("Button Title",for: .normal)
Is it possible to simply put my Label in my button's title?
Thanks in advance
You can add you custom label as subview to your button like Mike Alter mentioned in the comments like this (Note: Code is in Swift 3, but should be easy to adopt to Swift 2.*. Hints are in the code comments):
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let smallSquare = CGSize(width: 30, height: 30)
let button = UIButton(frame: CGRect(origin: .zero, size: smallSquare))
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .red
// add the button to your view
view.addSubview(button)
// set constraints of your button
button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.translatesAutoresizingMaskIntoConstraints = false
label.center = CGPoint(x: 160, y: 284)
label.textAlignment = .center
label.text = "I'm a test label"
// add the label to your button
button.addSubview(label)
// set constraints of your label
label.centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: button.centerYAnchor).isActive = true
}
}
Result with your custom values looks like this (Just added the red background of the button so you see the frame of the button compared to the label frame):
Your label has a text property. You used it to set a value and you can also use it to get the value. The text is optional, so you need to unwrap.
let labelText = label.text ?? ""
button.setTitle(labelText, for: .normal)
if let textFromLabel = yourCustomLabel.text {
yourButton.setTitle(textFromLabel, .normal)
}
is what I'll suggest you to do

Multiline Navigationbar Title

I am trying to set the title label in my navigation bar to allow multiple lines. I have custom navigation controller code that I am placing the multiline code into. I know that the code already there works, but my multiline part is not working.
let titleLabel = UILabel()
titleLabel.frame = CGRectMake(0, 0, self.navigationBar.frame.width, self.navigationBar.frame.height * 2)
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = .ByWordWrapping
navigationItem.titleView = titleLabel
But the text still runs off at the end. I've also tried putting this into the individual view controller itself, adding self.navigationController?. in front of navigationItem with the same results.
Is there something I'm missing in my code that would keep the title label from using multiple lines?
Here is a code example of how you can create a multiline navigationBar title
let label: UILabel = UILabel(frame: CGRectMake(0, 0, 400, 50))
label.backgroundColor = UIColor.clearColor()
label.numberOfLines = 2
label.font = UIFont.boldSystemFontOfSize(16.0)
label.textAlignment = .Center
label.textColor = UIColor.whiteColor()
label.text = "This is a\nmultiline string for the navBar"
self.navigationItem.titleView = label
Swift 5.x:
let label = UILabel()
label.backgroundColor = .clear
label.numberOfLines = 2
label.font = UIFont.boldSystemFont(ofSize: 16.0)
label.textAlignment = .center
label.textColor = .white
label.text = "This is a\nmultiline string for the navBar"
self.navigationItem.titleView = label
This is doable in a storyboard. Just drag a UIView into the Navigation bar, then drag a UILabel onto it in the document outline, set lines to 2 and alignment to center.
Use this to get the label position exactly as you want it:
let labelWidth = navBar.bounds.width - 110
let label = UILabel(frame: CGRect(x:(navBar.bounds.width/2) - (labelWidth/2), y:0, width:labelWidth, height:navBar.bounds.height))
label.backgroundColor = UIColor.clear
label.numberOfLines = 0
label.font = UIFont.boldSystemFont(ofSize: 13.0)
label.textAlignment = .center
label.textColor = UIColor.black
label.lineBreakMode = .byWordWrapping
label.text = loadedName
navBar.topItem?.title = nil
navBar.addSubview(label)
the 110 value in the top line is the spacing you want either side of the label.
swift 5+ very easy solution
func titleMultiLine(topText: String, bottomText: String) {
// let titleParameters = [NSForegroundColorAttributeName : UIColor.white,
// NSFontAttributeName : UIFont.<Font>]
// let subtitleParameters = [NSForegroundColorAttributeName : UIColor.<Color>(),
// NSFontAttributeName : UIFont.<Font>]
let titleParameters = [NSAttributedString.Key.foregroundColor : UIColor.white]
let subtitleParameters = [NSAttributedString.Key.foregroundColor : UIColor.white]
let title:NSMutableAttributedString = NSMutableAttributedString(string: topText, attributes: titleParameters)
let subtitle:NSAttributedString = NSAttributedString(string: bottomText, attributes: subtitleParameters)
title.append(NSAttributedString(string: "\n"))
title.append(subtitle)
let size = title.size()
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
titleLabel.attributedText = title
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
navigationItem.titleView = titleLabel
}
Function Calling
self.titleMultiLine(topText: "I am top text Title", bottomText: "bottom 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