Showing posts with label Label. Show all posts
Showing posts with label Label. Show all posts

Thursday, February 21, 2019

Clickable Label

We want a clickable label, add this line.
la.userInteractionEnabled=true
When clicked, we want it open new class.
Declare label.
var la: UILabel!
Set position, color text.
la = UILabel(frame: CGRect(x: 100, y: 30, width: 280, height: 25))
la.text = "Touch to open new class"
la.textColor = UIColor.orangeColor()
la.userInteractionEnabled=true
view.addSubview(la)
This is function to open new class.
func tap (g:UIGestureRecognizer) {
let vc = second()
self.presentViewController(vc, animated: true, completion: nil)
    }
Add this line in to viewDidLoad.
let t = UITapGestureRecognizer(target:self, action:#selector(ViewController.tap(_:)))
la.addGestureRecognizer(t)

Label now open a new class when we click.

Ajust text in Label Swift

To set text to label.
la.text = “This is example text
To color text.
la.textColor = UIColor.blueColor()
To change font, color, text size.
let t="Text to change font"
let at=NSMutableAttributedString(string: t , attributes: [NSForegroundColorAttributeName: UIColor.blueColor(), NSFontAttributeName: UIFont(name: "Arial", size: 15.0)!])
 la.attributedText(at, forState: .Normal)
To make bold text.
la.font = UIFont.boldSystemFontOfSize(17)
To make italic text.
la.font = UIFont.italicSystemFontOfSize(17)
To make text center.
la.textAlignment = NSTextAlignment.Center
To make label has many lines and high enough.
la.numberOfLines = 0
la.sizeToFit()
To make border, color border.
la.layer.borderColor = hex("#6699cc").CGColor
la.layer.borderWidth = 1

Function hex to use hex code can see here.

Center a view

To make text center label, we use this line
la.textAlignment = NSTextAlignment.Center
To make label center screen, use this
ima.center = CGPoint(x: view.center.x, y:250)
There’s another way, first get screen width
let r = UIScreen.mainScreen().bounds.size.width
If label width 240, declare a variable name margin
let margin = (Int(r) - 240)/2
Use this variable to set label margin.
la = UILabel(frame: CGRect(x: margin, y: 60, width: 240, height: 25))
This way can use to every view when you know it’s width.