Custom tab button position error on iphone x - ios

I add custom button to my tabbar with following this answer.
var menuButtonFrame: CGRect = menuButton.frame
//menuButtonFrame.origin.y = tabBar.frame.y + tabBar.frame.height - menuButtonFrame.height
menuButtonFrame.origin.y = view.bounds.height - menuButtonFrame.height
menuButtonFrame.origin.x = self.view.bounds.width / 2 - menuButtonFrame.size.width / 2
menuButton.frame = menuButtonFrame
menuButton.backgroundColor = Colors.mainColor
menuButton.layer.cornerRadius = menuButtonFrame.height/2
self.view.addSubview(menuButton)
when i tested on simulator it works good. but when i tested on Iphone X simulator it displays under tabbar.
I tried to align buttons origin.y value to tabbar bottom (commented line) but it didn't work again.
Should i use iphone x specific alignment or is there more clean solution for this.

Don't add centerButton in UIView. Add in tabBar
func addMenuButton() {
let menuWidth: CGFloat = 64 //let height & width same as 64
let menuButton = UIButton(frame: CGRect(x: (tabBar.frame.width / 2) - (menuWidth / 2), y: 0, width: menuWidth, height: menuWidth))
menuButton.backgroundColor = .red
menuButton.layer.cornerRadius = menuWidth/2
tabBar.addSubview(menuButton) //Add in tabBar instead of UIView
}

Related

How to set custom title view to center of navigation bar

I am trying to add custom view (Label) as title view of navigation item.
but it is not appearing in centre
func setupNavigationMultilineTitle(title:String) {
let autoscrollLabel = EFAutoScrollLabel()
autoscrollLabel.text = title
autoscrollLabel.textAlignment = .center
autoscrollLabel.backgroundColor = .red
autoscrollLabel.font = AppTheme.Fonts.font(type: .Medium, size: 15)
autoscrollLabel.textColor = AppTheme.Colors.ColorsOfApp.header_color.color
autoscrollLabel.frame = CGRect(x: 0, y: 0, width:((self.navigationController?.navigationBar.frame.size.width ?? 0) - (self.navigationItem.leftBarButtonItem?.customView?.frame.width ?? 0) * 2) , height: 40)
self.navigationItem.titleView = autoscrollLabel
}
I have tried to use deduct width of custom view to show it in center but unfortunately it is not working.
I have also tried to get self.navigationItem.leftBarButtonItem.width but it returns 0. I confirmed that there is leftBarbutton item with po self.navigationItem.leftBarButtonItem
EDIT
This solves issue
autoscrollLabel.frame = CGRect(x: self.view.center.x - 125, y: 0, width: 250 , height: 40)
But I need dynamic solution
Any help would be appreciated
I debugged your scenario, hope it helps you and other developers,
When we assign tittleView width by calculating the space left after subtracting space of items, margins, padding etc then iOS calculate titleView X from the right side i.e. titleview.x = rightItem.x - width and we are expecting it like titleview.x = navbar.width/2 - width/2.
Please look below sample test cases.
Calculate width
let maxItemOnEitherSide = max(arrLeftItems.count, arrRightItems.count)
let widthOfItem : CGFloat = 30.0
let pading : CGFloat = 40
let aWidth : CGFloat = (self.navigationController?.navigationBar.frame.width)! - CGFloat(maxItemOnEitherSide) * widthOfItem * 2.0 - pading
let lblNavTitle = UILabel(frame: CGRect(x: 0, y: 0,
width: aWidth,
height: 40))
Case 1 : arrLeftItems.count = 1 and arrRightItems.count = 0.
Output :
Case 2 : arrLeftItems.count = 0 and arrRightItems.count = 1.
Hope above cases clear you out what we are expecting and what we are getting and the calculation that I wrote in first para i.e. titleview.x = rightItem.x - width.
Conclusion :
If rightBarItems have more items than leftBarItems then titleview will be in center, so you wont need to do anything but if leftBarItems have more items than rightBarItems then add blank items in right side to make it balance. It is weird for developers but seems like its the only solution.
Check the final output.
View Heirarchy
Output
If your navigation Item is part of a UINavigationController you could try
self.navigationController?.navigationBar.topItem?.leftBarButtonItem?.width ?? 0.0
Add my version code based on #dahiya_boy answers.
In my case, I have a custom button that has a more 30-width size. So, rather than multiply it by 30, I find a max from left and right items to find the max.
Below is the code:
func setCenterTitle(_ title: String) {
let navWidth = (navigationController?.navigationBar.frame.width).orZero
let leftItemsWidth = leftBarButtonItems.orEmptyArray.reduce(0) {
$0 + ($1.customView?.frame.width).orZero
}
let rightItemsWidth = rightBarButtonItems.orEmptyArray.reduce(0) {
$0 + ($1.customView?.frame.width).orZero
}
let maxItemsWidth = max(leftItemsWidth, rightItemsWidth)
let padding: CGFloat = 40
let labelWidth = navWidth - (maxItemsWidth * 2) - padding
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: labelWidth, height: 40))
titleLabel.text = title
titleLabel.textAlignment = .center
titleLabel.font = UIFont.boldSystemFont(ofSize: 16)
self.titleView = titleLabel
}

Swift 4 - Button over Tab Bar Item

I am trying to position a custom button over one of the item of my Tab bar.
func setupMiddleButton() {
let numberOfItems = CGFloat(tabBar.items!.count)
let tabBarItemSize = CGSize(width: tabBar.frame.width / numberOfItems, height: tabBar.frame.height)
let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: tabBarItemSize.width, height: self.tabBar.frame.size.height))
var menuButtonFrame = menuButton.frame
menuButtonFrame.origin.y = self.view.bounds.height - menuButtonFrame.height
menuButtonFrame.origin.x = self.view.bounds.width/2 - menuButtonFrame.size.width/2
menuButton.frame = menuButtonFrame
menuButton.backgroundColor = UIColor.white
self.view.addSubview(menuButton)
self.view.layoutIfNeeded()
My issue is that with the previous code the button is not perfectly over the bar item (see picture):
Any suggestion? I really don't know how else to try.
Thank you!
I notice that this screenshot is of an iPhone X Simulator, which has a different layout at the bottom of the screen.
Your code works well on any other iPhone. In iOS 11 they introduced what's called the "Safe area". When you calculate the size and origin for your button, you will have to take that into account.
When you calculate the origin.y for your buttonFrame, you have to subtract the height for the safe-area at the bottom, like this:
menuButtonFrame.origin.y = self.view.bounds.height - menuButtonFrame.height - self.view.safeAreaInsets.bottom
This won't solve your problem though, as your code probably runs in viewDidLoad, which happens before the view knows it's supposed be displayed on an iPhone X with a safe area.
You can override viewDidLayoutSubviews for this, and set the correct frame for your button each time that is called.
This will fix your issue:
class CustomTabBarViewController: UITabBarController {
let menuButton = UIButton(frame: CGRect.zero)
override func viewDidLoad() {
super.viewDidLoad()
setupMiddleButton()
}
func setupMiddleButton() {
let numberOfItems = CGFloat(tabBar.items!.count)
let tabBarItemSize = CGSize(width: tabBar.frame.width / numberOfItems, height: tabBar.frame.height)
menuButton.frame = CGRect(x: 0, y: 0, width: tabBarItemSize.width, height: tabBar.frame.size.height)
var menuButtonFrame = menuButton.frame
menuButtonFrame.origin.y = self.view.bounds.height - menuButtonFrame.height - self.view.safeAreaInsets.bottom
menuButtonFrame.origin.x = self.view.bounds.width/2 - menuButtonFrame.size.width/2
menuButton.frame = menuButtonFrame
menuButton.backgroundColor = UIColor.green
self.view.addSubview(menuButton)
self.view.layoutIfNeeded()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
menuButton.frame.origin.y = self.view.bounds.height - menuButton.frame.height - self.view.safeAreaInsets.bottom
}
}
I know it's tempting to simply call setupMiddleButton from inside viewDidLayoutSubviews, but do not do that. viewDidLayoutSubviews should not be used to create buttons etc., it should only be used to move them accordingly to the rest of the view. You might want to set the entire frame of menuButton inside viewDidLayoutSubviews rather than only the origin.y like I did, especially if you need to support rotation/landscape-mode. In this very simple example, updating origin.y is enough.

center element when pressed in a ScrollView

i really how to do a thing wich is probably easy..
I've a ScrollView with some button in it.
That's how i create all my button in the scrollview.
var buttonList = [UIButton]()
func createButton() {
let imageArray = fillImageArray()
var lastButtonWidth: CGFloat = 0
for index in 0..<6 {
let frame1 = CGRect(x: ((self.view.frame.size.width / 2) - 27.5) + CGFloat(index * 70), y: 0, width: 55, height: 55 )
let button = UIButton(frame: frame1)
button.setImage(imageArray[index], forState: .Normal)
button.tag = index
button.addTarget(parentViewController, action: #selector(ViewController.buttonClicked(_:)), forControlEvents: .TouchUpInside)
self.scrollView.addSubview(button)
lastButtonWidth = frame1.origin.x
buttonList.append(button)
}
self.scrollView.contentSize = CGSizeMake(lastButtonWidth + 55, 0)
}
I want when i press one of my button to center him and positioning correctly the other buttons.
example :
If i press on 5 i want this result :
the button 5 is moved to the center.
Now what I would suggest using is the scroll view method scrollView.scrollRectToVisible(CGRect, animated: Bool). This will move the scroll view to make a certain part of your content visible.
To create the CGRect you could do something like this:
let scrollWidth = scrollView.frame.width
let scrollHeight = scrollView.frame.height
let desiredXCoor = button.frame.origin.x - ((scrollWidth / 2) - (button.frame.width / 2) )
let rect = CGRect(x: desiredXCoor, y: 0, width: scrollWidth, height: scrollHeight)
scrollView.scrollRectToVisible(rect, animated: true)
My math may be a bit off, but the essence is that you use the size of the scrollView and the UIButton to create a CGRect for the scroll view to move to. This means when a button is clicked, you could use an implementation like this:
func myMethod() {
button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
}
func buttonClicked(sender: UIButton){
let scrollWidth = scrollView.frame.width
let scrollHeight = scrollView.frame.height
let desiredXCoor = sender.frame.origin.x - ((scrollWidth / 2) - (sender.frame.width / 2) )
let rect = CGRect(x: desiredXCoor, y: 0, width: scrollWidth, height: scrollHeight)
scrollView.scrollRectToVisible(rect, animated: true)
}
If adjusted properly to your project, this should allow you to do what you have outlined.
Hope this would help you.
In button action method write below code.
func buttonClicked(sender:UIButton) {
for view in self.scrollView.subviews {
if view.isKindOfClass(UIButton) && view.tag == sender.tag {
let xCenter = max(0, (view.center.x - self.scrollView.frame.width/2))
self.scrollView.setContentOffset(CGPointMake(xCenter, self.scrollView.contentOffset.y), animated: true)
break;
}
}
}
I suppose you want the button touched to be placed in the center,so there is a easy solution, you can use the button's center.x - scrollview.width / 2 as the offsetX to construct the contentOffset and take two boundary situation into consideration:offsetx < 0 and offsetx + scrollview.width > scroll.contentSize.width
Ok i just found by myself.
let centerScrollView = scrollView.frame.size.height * 2
UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: {
self.scrollView.contentOffset = CGPoint(x: sender.frame.origin.x - centerScrollView, y: sender.frame.origin.y)
}, completion: nil)
and it's perfectly center. Thx everyone.

How to center UIButton in Swift?

I have this code for my UIButton. What should I change in my CGRectMake to set my UIButton in the center of the screen for all screen sizes?
let loginBtn = UIButton(frame: CGRectMake(60, 360, 240, 40))
loginBtn.layer.borderColor = UIColor.whiteColor().CGColor
loginBtn.layer.borderWidth = 2
loginBtn.titleLabel!.font = UIFont.systemFontOfSize(24)
loginBtn.tintColor = UIColor.whiteColor()
loginBtn.setTitle("Login", forState: UIControlState.Normal)
self.view.addSubview(loginBtn)
For your place uibutton center of your view , update your cgrectmake as bleow..
CGRectMake((self.view.frame.size.width - 240) / 2, (self.view.frame.size.height - 40) / 2,240,40)
or
You can add one line after your code
loginBtn.center = self.view.center
For SignUp Button :
 
signup.frame = loginBtn.bounds
signup.center = CGPointMake(loginBtn.center.x, loginBtn.center.y + loginBtn.frame.size.height + 10)
Set your UIButton's center to the center of the view it is in.
loginBtn.center = view.center
You need add the following line prior to self.view.addSubview(loginBtn).
loginBtn.center = self.view.center
This will center the button across the whole screen, not just the view it's in:
let verticalCenter: CGFloat = UIScreen.mainScreen().bounds.size.height / 2.0
let horizontalCenter: CGFloat = UIScreen.mainScreen().bounds.size.width / 2.0
loginBtn.center = CGPoint(x: horizontalCenter, y: verticalCenter)
Edit:
As #LeoDabus pointed out, this can be compacted by using the midX and midY properties on CGRect:
let verticalCenter: CGFloat = UIScreen.mainScreen().bounds.midY
let horizontalCenter: CGFloat = UIScreen.mainScreen().bounds.midX
For Swift 4
#IBOutlet weak var btStart: UIButton!
on the middle of any screen (any device)
btStart.center = self.view.center
OR
btStart.center.x = self.view.center.x
btStart.center.y = self.view.center.y
on the center by x and 25 percent from top
btStart.center.x = self.view.center.x
btStart.center.y = self.view.center.y / 2
I found this to be the best solution for me..
Swift 4
myButton.center.x = self.view.frame.midX
myButton.center.y = self.view.frame.midY
I found if I need to center things quite often, I usually use a generic solution.
extension UIViewController {
func centerComponent(_ component: AnyObject) {
let customView = component as! UIView
customView.center.x = self.view.frame.midX
customView.center.y = self.view.frame.midY
}
}
then you can call it from any UIViewcontroller inside a function like so:
centerComponent(myButton)

ios: Center view in its superview

I'm trying to center my subview with a button in itssuperview. So I want the center of the subview be the center of the superview. I'm trying that with following code:
override func viewDidLoad() {
self.view.backgroundColor = UIColor.redColor()
var menuView = UIView()
var newPlayButton = UIButton()
//var newPlayImage = UIImage(named: "new_game_button_5cs")
var newPlayImageView = UIImageView(image: UIImage(named: "new_game_button_5cs"))
newPlayButton.frame = CGRectMake(0, 0, newPlayImageView.frame.width, newPlayImageView.frame.height)
newPlayButton.setImage(newPlayImage, forState: .Normal)
newPlayButton.backgroundColor = UIColor.whiteColor()
menuView.center = self.view.center
menuView.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2)
menuView.backgroundColor = UIColor.whiteColor()*/
menuView.addSubview(newPlayButton)
}
Unfortunately it doesent seem to work as this is the result:
UIView *subview = your View To Be Centered In Its SuperView;
UIView *superView = subview.superview;
subview.center = [superView convertPoint:superView.center
fromView:superView.superview];
If view is nil(on fromView:), this method instead converts from window base coordinates. Otherwise, both view and the receiver must belong to the same UIWindow object.
NOTE: If you use the auto layout stuff, then you have to change the constraints . not the frame or center.
Good Luck :)
Try removing your view width from your superview width, e.g.:
var width: CGFloat = (self.view.bounds.size.width / 2)
// (here goes your view width that you want centralize)
menuView.center = CGPointMake(width, self.view.bounds.size.height / 2)
My working code
vRate = superview
rcRating = view ( that I want to centralize in vRate )
self.rcRating = AMRatingControl(location: CGPoint(x: 0, y: 0), andMaxRating: 5)
self.vRate.addSubview(self.rcRating)
var width: CGFloat = (self.vRate.bounds.size.width / 2) - self.rcRating.bounds.size.width
self.rcRating.center = CGPointMake(width, self.vRate.bounds.size.height / 2)

Resources