简体   繁体   中英

How to Put UIView subview In Places

For Example lets say I have a UIView I would like to display

view.addSubview(line)

Now I want t to be able to display that UIView in the top right corner. Let say inside the right side of the navigation bar. How would I do this? Or even in a specific place.

Add a frame for your subview, as :

Objective-C:

line.frame = CGRectMake(0, 0, 50, 50);

Swift 3:

CGRect(x:0,y:0,width: 50,height: 50) 

This will add your line subview on top left corner with height 50 and width 50.

You can use

self.navigationController?.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: lineMat)

to set up a view on navigationBar right side.

Also you can add the lineMat view on UIApplication.shared.keyWindow

Just use UIApplication.shared.keyWindow?.addSubview(lineMat) and set up to lineMat view's frame.

You will need to calculate the frame or need to give constraints to that view.

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

From above you can get screenwidth and you can set your y to 0. Let say width height of your view is 20. So, frame would be like below.

yourView.frame = CGRect(x:screenwidth - 20 , y: 20, width:20 , height: 20)

You can change the frame as per your requirements.

For navigation bar there is a better way to do it by adding right bar item. Look below code how to do it.

self.navigationItem.rightBarButtonItem = rightButtonItem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM