

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to add a border to the top and bottom of an iOS View?
In this post we will learn how to add top and bottom border to view.
In this example we will take as sample view and add borders to it.
Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “AddBorderTopAndBottom”
Step 2 − Open Main.storyboard add a UIView to it as shown below.
Step 3 − Add one @IBOutlet for the view, name it centerView.
Step 4 − We will write separate method to add borders to this view. To add borders to this view we will create two layers with desired thickness. We will set the frame of these two layers to top and bottom of the view. We will set the desired background color of the borders on these layers and add these layers as subLayers to the view.
So create a function addTopAndBottomBorders and add the following lines
func addTopAndBottomBorders() { let thickness: CGFloat = 2.0 let topBorder = CALayer() let bottomBorder = CALayer() topBorder.frame = CGRect(x: 0.0, y: 0.0, width: self.centerView.frame.size.width, height: thickness) topBorder.backgroundColor = UIColor.red.cgColor bottomBorder.frame = CGRect(x:0, y: self.centerView.frame.size.height - thickness, width: self.centerView.frame.size.width, height:thickness) bottomBorder.backgroundColor = UIColor.red.cgColor centerView.layer.addSublayer(topBorder) centerView.layer.addSublayer(bottomBorder) }
As you can see, we have set the appropriate thickness, frame and color for the layers and added them as sublayer.
Step 5 − Call addTopAndBottomBorders method in viewDidAppear of the ViewController class.
override func viewDidAppear(_ animated: Bool) { addTopAndBottomBorders() }
Step 6 − Run the project, you should be able to see the top and bottom borders of the center view.
- Related Questions & Answers
- How to add a border to the top and bottom of an Android View?
- Set the left, right, top and bottom padding of an element
- How to create a Border, Border radius, and shadow to a UIView in iPhone/iOS?
- How to get the dimensions of a view in iOS App?
- How to set the width of the bottom border with JavaScript?
- How to set the style of the bottom border with JavaScript?
- How to add a border to an image with CSS?
- How to align views at the bottom of the screen in iOS
- CSS3 top to bottom Gradient
- How to change the size of an image and add a border in OpenCV using C++?
- How to set background color of a View in iOS App?
- How to set the color of the bottom border in JavaScript DOM?
- How to set the width of the top border with JavaScript?
- How to set the color of the top border with JavaScript?
- How to set the style of the top border with JavaScript?