
- iOS Tutorial
- iOS - Home
- iOS - Getting Started
- iOS - Environment Setup
- iOS - Objective-C Basics
- iOS - First iPhone Application
- iOS - Actions and Outlets
- iOS - Delegates
- iOS - UI Elements
- iOS - Accelerometer
- iOS - Universal Applications
- iOS - Camera Management
- iOS - Location Handling
- iOS - SQLite Database
- iOS - Sending Email
- iOS - Audio & Video
- iOS - File Handling
- iOS - Accessing Maps
- iOS - In-App Purchase
- iOS - iAd Integration
- iOS - GameKit
- iOS - Storyboards
- iOS - Auto Layouts
- iOS - Twitter & Facebook
- iOS - Memory Management
- iOS - Application Debugging
- iOS Useful Resources
- iOS - Quick Guide
- iOS - Useful Resources
- iOS - Discussion
How to give dynamic height to UIlabel programmatically in swift?
To give a dynamic height to an UIlabel in swift we can use the frame property of UILabel. We can create a frame using the CGRect which allows us to give different variables like x position, y position, width, and height.
Let’s create a label and add it as a subview to our view.
let label = UILabel() label.frame = CGRect(x: 10, y: 40, width: 200, height: 50) label.backgroundColor = colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1) label.textColor = colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 1) label.text = "Custom label" self.view.addSubview(label)
We can embed this in a function as well, and create an extension too.
func makeLabel(atX x: Double, andY y: Double,width: Double, height: Double) -> UILabel { let label = UILabel() label.frame = CGRect(x: x, y: y, width: width, height: height) label.backgroundColor = colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1) label.textColor = colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 1) label.text = "Custom label" return label }
We can use it inside the view controller along with the previous code, and this is how it looks on the device.
self.view.addSubview(makeLabel(atX: 10, andY: 100, width: 250, height: 100))
- Related Articles
- How to add constraints programmatically using Swift
- Programmatically go back to the previous ViewController in Swift
- How to set height equal to the dynamic width (CSS fluid layout) in JavaScript?
- How to add line break for UILabel in iOS/iPhone?
- Changing the text of UIButton programmatically in Swift
- How to use Bold & Non-Bold Text In A Single UILabel in iOS/iPhone?
- Adding Navigation Bar programmatically iOS using Swift
- How to use dynamic GUID in Postman?
- How to quit application programmatically?
- How to set max_connections in MySQL Programmatically?
- How to create directory programmatically in Android?
- How to click camera programmatically in android?
- How to disable ScrollView Programmatically in Android?
- how to initialize a dynamic array in java?
- How to define dynamic data types in C#

Advertisements