ok, I have added a button to the .swift storyboard, I have then added the following code to my ViewController.swift
#IBOutlet weak var HelloButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
HelloButton.frame.origin.x = view.frame.size.width / 2
}
However when I test it on my iPhone 5s it moves it to the right of my screen and does not make it centered. I am unsure what I need to do to make the button centered.
Yes this is my first helloWorld app, and maybe over my head, but I understand web programing, and I understand to make it center automaticilly I need to have the screen view width total and the button width. I then need to say to the button to divide the screen view width by 2.
for example in CSS we do this
#button{margin:0 auto;}
but this is not HTML or CSS. IT'S SWIFT3
Try this:
HelloButton.center.x = view.frame.width/2
Yours is not correct because the origin.x is the first point (top left) of the button view, not the center of the view, you can change it's background color to different color to see it
Also, the variable name should be lowerCase, followed by code convention
You should be using Autolayout for accomplishing what you want and the way you do is like the following in your ViewController inside of Main.storyboard: (control + left mouse click -> dragging the blue line upwards and then releasing the control and left mouse click, you will see the popup)
In the popup select the options:
Center Horizontally In Container
Center Vertically in Container
But if you want to do it programmatically, do it in viewWillLayoutSubviews method:
class ViewController: UIViewController {
#IBOutlet weak var button: UIButton!
override func viewWillLayoutSubviews() {
super. viewWillLayoutSubviews()
button.center = view.center
}
}
In your project Autolayout is enabled? if Auto Layout enabled then Change UI in viewdidLoad: may not give appropriate result. use -viewWillLayoutSubviews method to do UI task, it you want to center your button
myButton.center = self.view.center
Hope it will work.
Add the code to viewDidAppear that way the actual view has shown up. Also, you should use button.center.x instead of button.frame.origin.x if you want to center it
Related
What I want to to: I want to drag down the whole view of a viewController to dismiss to the parent viewController using a pan gesture recognizer.
The Problem: When I drag the view down, the navigationBar decreases its height and does not look good. When the view returns to its original position, the navigationBar returns to the default size. I want the navigationBar to stay at its size. I also tried to use the new large titles and some other properties of the navigationController/-bar, but that did not solve it.
Note: Everything worked fine already before iOS 11.
My code:
override func viewDidLoad() {
super.viewDidLoad()
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(dragViewDown(_:)))
navigationController!.view.addGestureRecognizer(panGesture)
}
#IBAction func dragViewDown(_ gesture: UIPanGestureRecognizer) {
if let dragView = gesture.view {
let translation = gesture.translation(in: dragView)
dragView.center.y = (dragView.center.y + translation.y)
gesture.setTranslation(CGPoint.zero, in: dragView)
}
}
This test project only has one viewController and does not provide the dismissal, but the problem is the same as in my working project.
I also uploaded the project to GitHub: https://github.com/maddinK7/navitationBar-pull-down-problem
Does anyone have an idea how to solve this? Thanks in advance.
I want the navigationBar to stay at its size
It is staying at its size. If you check the navigation bar's bounds size height before, during, and after the drag, you will see that it remains the same (probably 44) at all times. What's changing is the drawing extension that causes the drawing of the nav bar to extend up behind the status bar. It can't do that when you pull the whole thing away from the top of the screen, because it is not at the top next to the status bar any more. iOS 11 is more strict about the way it performs this drawing extension, probably because it has to do it in a special way on the iPhone X.
So, let's make sure you're doing this correctly:
Make sure that the navigation bar has a top constraint pinned to the safe area layout guide's top, with a constant of zero.
Make sure that the navigation bar has a delegate that returns .topAttached from position(forBar:).
If you are doing both those things and it doesn't help, you'll have to implement this in some other way entirely. Making the view directly draggable like this, without a custom parent view controller, was always dubious.
When UINavigationController attached top, system will add safe area top margin in the navigation background.
(NOTICE: Background margin will not changed when offset value is between 1 and 0)
So you have to handle attached/detached top event by handle gesture offset to change the right offset and content insets.
You can try the solution in my lib example. ;)
My example include UITableViewController in the UINavigationController, so it will relatively complex.
https://github.com/showang/OverlayModalViewController
What is the best approach for attaching a UIButton on top of UIScrollView or UITableView so when the view is scrolled, the button stays in its place.
Here examples below:
UIButton stays in the right bottom corner when the view is scrolled.
google+ app example
yahoo mail app example
I think this should work. Lay Out your button in a view that is outside of the tableviewcontroller. Then drag an outlet to the tableviewcontroller file. Then add it in code. This code would hold it at the top of the screen.
#IBOutlet var buttonView: UIView!
override func viewDidLayoutSubviews() {
self.view.addSubview(buttonView)
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
var rect = self.buttonView.frame
rect.origin.y = max(0,scrollView.contentOffset.y + scrollView.contentInset.top)
self.buttonView.frame = rect
}
Thank you all for great answers!
I got it worked through storyboard by moving the button from scrollView to View itself. That way it's attached on UIView and it's independent of scrollview.
storyboard snapshot
So now the structure is:
- View
- ScrollView
- Button
Before it was:
- View
- ScrollView
- Button
There are many ways to go about doing this but two that I use most often are as follows.
One approach is embedding the view controller within a navigation controller. This will set a bar on the top and bottom if you choose that you can place bar button items upon.
Another approach is to place a UIView along the top and snap the constraints to the left, right, and top with 0 no-margin. Then set the height. I usually use 40px for the height but you can use what is applicable to your needs. After that you can place a button in that UIView and then set constraints on it to keep in in place.
In my experience, this isn't reliably possible to do with the scrollView itself.
My solution is usually to put anything that needs to float above the tableView/scrollView in a plain ViewController that also contains the tableView/scrollView parent.
If you're using storyboards with a UITableViewController scene, this will likely mean you need to use another scene with UIViewController with a container that has your UITableViewController.
For UITableView use tableHeaderView. For UIScrollView you need to create a separate view not in the scroll view's hierarchy.
Another solution is to put your UIButton in a UIToolbar, and then make the toolbar a child of the UINavigationController's view. After that, in viewDidLayoutSubviews, you can set the rect of the toolbar to sit just below the navigation bar and offset the top of the UIScrollView or UITableView.
Add button which you want in the storyboard.
Design your scrollview
self.view.sendSubviewToBack(scrollViewObj)(in the code)
This worked for me.
I have a UIScrollView with a UIView for content inside of it. On the UIView, I have some buttons I'm using for a menu. Everything works great until I rotate to landscape. Once I rotate, the buttons on the UIView can't be clicked but the top buttons still work. I'm assuming it's because the UIView holding the buttons isn't being resized so it's not responding to taps. This can be seen in the 3d exploded image (Image 4). I have tried all of these lines of code to try to get it to resize, buttons have worked (code is commented because I tried different combos).
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
//hides and displays tab bar on orientation changes
if toInterfaceOrientation.isLandscape {
tabBarController!.tabBar.hidden = true
//self.navigationController!.view.sizeToFit()
//self.navigationController!.view.setNeedsLayout()
//self.viewForContent.setNeedsLayout()
//self.viewForMenuItems.setNeedsLayout()
//self.viewForContent.contentSize = CGSizeMake(900, 900)
//self.viewForContent.setNeedsLayout()
}
else if toInterfaceOrientation.isPortrait {
tabBarController!.tabBar.hidden = false
//self.navigationController!.view.setNeedsLayout()
//self.viewForContent.setNeedsLayout()
//self.viewForMenuItems.setNeedsLayout()
//self.viewForContent.contentSize = CGSizeMake(900, 900)
//self.viewForContent.setNeedsLayout()
}
}
Also I have this in the DidLoad and DidLayoutSubviews. When I comment out the DidLayoutSubviews the buttons work again, but the scrollview isn't large enough to allow me to scroll to the bottom buttons when in landscape
override func viewDidLoad() {
super.viewDidLoad()
let size = UIScreen.mainScreen().bounds.size
viewForContent.contentSize = CGSizeMake(size.width, 458)
// Do any additional setup after loading the view.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let size = UIScreen.mainScreen().bounds.size
viewForContent.contentSize = CGSizeMake(size.width, 458)
}
The My Information, My Staff, My Colleagues, and My Residents are the buttons that work in landscape mode.
I have used autolayout constraints to setup the views. Also, I am using XCode7 with Swift.
Any help would be appreciated
Thanks
First I setup my views as outlined in the link posted above in the comments by Kusul (Thank you). But when I did this and added the buttons to the content view they wouldn't show on when the screen was rotated to landscape because they were off of the bottom and the UIScrollView didn't "grow".
I figured out that I needed to add a bottom constraint to my last button. So the last button now has a constraint to the top and the bottom. This forced the scroll view to "grow" to the proper size. I could then eliminate setting the size in the didLoad and didLayoutSubviews. Thanks for the help
I have the following UIViewController which i am doing in story board.
The problem i am facing here is that when i try to swipe right on tv remote my UIImageView does not get any focus. Infact no focus event happen, it try to put some logs in
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator)
but there is no focus event updated. Earlier i have UIImageView directly added on self.view in storyboard but i read somewhere the UIImageView itself is not focusable so i put my UIImageView inside another UIView, but it still does not gets any focus. I have aligned top edges of UIView which contains UIImageView and UITextView.
Any help will be highly appreciated
On a side note i also tried to do with UIFocusGuide but that didn't work also. I think i don't need to use UIFocusGuide because it a basic right swipe focus thing.
UIImageView is not by default focusable, and will not get focus effect, you can do two things to make it focusable.
Subclass UIImageView and in subclass override canBecameFocused and
return YES, and then override didUpdateFoucsInContext and update appearance for focus state, like if focus make it bigger or change color etc.
Second option is add it to a view which is focusable and then set imageView.adjustImageWhenAncestorFocused = YES also set clipToBounds = NO on superview
So In your case as you are adding imageView to a view then that view should return YES/True from canBecameFocused.
#C_X is right. The most important thing is that if UIImageView is added to self.view then don't forget to subclass self.view and override the canBecameFofused method.
I am trying to change the height of there navigation bar for my app.
Currently the height is fixed to 44. I can change the width from Xcode but not the height.
I have no idea how to change this. Very new to iOS development.
Can anyone please help?
simply dragged and dropped it on my view
In that case, the simplest way is with constraints. Just give it a height constraint (along with the other constraints that position it). No code required! Here's an example:
That was achieved with no code at all. It's all done with constraints:
We are pinned to the top and sides of the superview, along with height constraint of 100.
Try this :
import UIKit
class YourViewController : UIViewController {
var navBar: UINavigationBar = UINavigationBar()
override func viewDidLoad() {
super.viewDidLoad()
self.setNavBarToTheView()
// Do any additional setup after loading the view.
self.title = "test test"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setNavBarToTheView() {
self.navBar.frame = CGRectMake(0, 0, 320, 50) // Here you can set you Width and Height for your navBar
self.navBar.backgroundColor = (UIColor.blackColor())
self.view.addSubview(navBar)
}
}
I know this makes no sense, however this is what I did ( worked without laying down constraints ).
select your View Controller.
Open Show the attributes inspector
for top bar select any tab bar (I'm choosing translucent Tab Bar).
within the show the object library drag and drop the navigation item on the View Controller. (If done right, should look like image 3)
Additionally ( fyi ), you can add a constraint to your button, etc. with using no margins and top being set to 0.