Eliminate repeated code Swift 3 - ios

I have multiple navigation controllers and their root view controllers in my app. I want each navigation bar to have social media buttons closely placed on the right side of the bar. For the same I have used this code to show the buttons in 1 view controller:
let fbImage = UIImage(named: "Facebook.png")!
let twitterImage = UIImage(named: "Twitter.png")!
let youtbImage = UIImage(named:"YouTube.png")!
let fbBtn: UIButton = UIButton(type: .custom)
fbBtn.setImage(fbImage, for: UIControlState.normal)
fbBtn.addTarget(self, action: #selector(HomeViewController.fbBtnPressed), for: UIControlEvents.touchUpInside)
fbBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let fbBarBtn = UIBarButtonItem(customView: fbBtn)
let twitterBtn: UIButton = UIButton(type: .custom)
twitterBtn.setImage(twitterImage, for: UIControlState.normal)
twitterBtn.addTarget(self, action: #selector(HomeViewController.twitterBtnPressed), for: UIControlEvents.touchUpInside)
twitterBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let twitterBarBtn = UIBarButtonItem(customView: twitterBtn)
let youtbBtn: UIButton = UIButton(type: .custom)
youtbBtn.setImage(youtbImage, for: UIControlState.normal)
youtbBtn.addTarget(self, action: #selector(HomeViewController.youtubeBtnPressed), for: UIControlEvents.touchUpInside)
youtbBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let youtbBarBtn = UIBarButtonItem(customView: youtbBtn)
self.navigationItem.setRightBarButtonItems([youtbBarBtn, twitterBarBtn, fbBarBtn], animated: false)
Now I want the same buttons on all navigations bars. I can easily copy this code and respective target methods in viewDidLoad() of each view controller, but too much code is getting repeated. So how can avoid this situation?
I am using Swift 3. I am new to iOS. Any help will be appreciated!

Most duplications are solved by using functions. The first step is to extract that code into a function, the second step is to use the same function from multiple places.
You can add it to an extension, for example:
extension UIViewController {
func addShareButtons() {
...
self.navigationItem.setRightBarButtonItems([youtbBarBtn, twitterBarBtn, fbBarBtn], animated: false)
}
}
and only call
self.addShareButtons()
from every controller that needs the buttons.
You can add button handlers to the extension too.
Another method is to use a UIViewController subclass but that's always a problem if you want to use a UITableViewController subclass.

You can design a custom navigation controller and add these code to the navigation controller. inherit the navigation controller to your storyboard or programmatically where you want to use.
//sample code
class "YourNavigationCorollerName": UINavigationController, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
//declare here you code, what you want
}
}

Assuming that these buttons ALWAYS have the same behavior, you can create a custom class for them, and place the repeated code there. For instance:
class FacebookButton : UIButton {
override init() {
super.init()
self.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
self.setImage(UIImage(named: "Facebook.png")!, for: .normal)
}
}
...I think the compiler will yell at you for initializing a UIView without a decoder and frame, but hopefully you get the idea.
To improve on this, you could 1) create a custom UINavigationController with the UIBarButtonItems you want to use, and reuse that controller, and/or 2) create a protocol like the following:
protocol FacebookBtnHandler {
func fbBtnPressed()
}
...and have any relevant VCs conform to it. This would allow you to assign the target and selector for the button in the FacebookButton init method, where you assign the image and frame, and hence prevent repetition of that line, as well.

Try to implement bar button by creating subclass of UIBarButton
class Button: UIBarButtonItem {
convenience init(withImage image : UIImage,Target target: Any, andSelector selector: Any?){
let button = UIButton(type: .custom)
button.setImage(image, for: UIControlState.normal)
button.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
button.addTarget(target, action: selector, for: UIControlEvents.touchUpInside)
self.init(customView: button)
}
}
let fbImage = UIImage(named: "Facebook.png")!
let twitterImage = UIImage(named: "Twitter.png")!
let youtbImage = UIImage(named:"YouTube.png")!
let fbBtn = Button(withImage: fbImage, Target: self, andSelector: #selector(HomeViewController.fbBtnPressed))
let twitterBtn = Button(withImage: fbImage, Target: self, andSelector: #selector(HomeViewController.twitterBtnPressed))
let youtubeBtn = Button(withImage: fbImage, Target: self, andSelector: #selector(HomeViewController.youtubeBtnPressed))
self.navigationItem.setRightBarButtonItems([youtbBarBtn, twitterBarBtn, fbBarBtn], animated: false)
and make it for all your view controller
extension UIViewController {
func addButtons() {
// add above code
}
}

Related

Positioning view next to navigationTitle [duplicate]

I am trying to set an Image for bar button Item for that I have an image like:
with resolution 30 * 30 but while I assign this Image to Bar button Its looks like:
I have assigned image this way :
and If I try this way like making an IBOutlet for the button and set Image programatically form this question and code for that is:
// Outlet for bar button
#IBOutlet weak var fbButton: UIBarButtonItem!
// Set Image for bar button
var backImg: UIImage = UIImage(named: "fb.png")!
fbButton.setBackgroundImage(backImg, forState: .Normal, barMetrics: .Default)
but nothing happend with this,
Can anybody tell me what I am doing wrong?
or which is the batter way to do this?
I have achieved that programatically with this code:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//create a new button
let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
//set image for button
button.setImage(UIImage(named: "fb.png"), forState: UIControlState.Normal)
//add function for button
button.addTarget(self, action: "fbButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
//set frame
button.frame = CGRectMake(0, 0, 53, 31)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
}
//This method will call when you press button.
func fbButtonPressed() {
println("Share to fb")
}
}
And result will be:
Same way you can set button for left side too this way:
self.navigationItem.leftBarButtonItem = barButton
And result will be:
And if you want same transaction as navigation controller have when you go back with default back button then you can achieve that with custom back button with this code:
func backButtonPressed(sender:UIButton) {
navigationController?.popViewControllerAnimated(true)
}
For swift 3.0:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//create a new button
let button = UIButton.init(type: .custom)
//set image for button
button.setImage(UIImage(named: "fb.png"), for: UIControlState.normal)
//add function for button
button.addTarget(self, action: #selector(ViewController.fbButtonPressed), for: UIControlEvents.touchUpInside)
//set frame
button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
}
//This method will call when you press button.
func fbButtonPressed() {
print("Share to fb")
}
}
For swift 4.0:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//create a new button
let button = UIButton(type: .custom)
//set image for button
button.setImage(UIImage(named: "fb.png"), for: .normal)
//add function for button
button.addTarget(self, action: #selector(fbButtonPressed), for: .touchUpInside)
//set frame
button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
}
//This method will call when you press button.
#objc func fbButtonPressed() {
print("Share to fb")
}
}
An easy solution may be the following
barButtonItem.image = UIImage(named: "image")
then go to your Assets.xcassets select the image and go to the Attribute Inspector and select "Original Image" in Reder as option.
Similar to the accepted solution, but you can replace the
let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
with
let button = UIButton()
Here is the full solution, enjoy: (it's just a bit cleaner than the accepted solution)
let button = UIButton()
button.frame = CGRectMake(0, 0, 51, 31) //won't work if you don't set frame
button.setImage(UIImage(named: "fb"), forState: .Normal)
button.addTarget(self, action: Selector("fbButtonPressed"), forControlEvents: .TouchUpInside)
let barButton = UIBarButtonItem()
barButton.customView = button
self.navigationItem.rightBarButtonItem = barButton
Here's a simple extension on UIBarButtonItem:
extension UIBarButtonItem {
class func itemWith(colorfulImage: UIImage?, target: AnyObject, action: Selector) -> UIBarButtonItem {
let button = UIButton(type: .custom)
button.setImage(colorfulImage, for: .normal)
button.frame = CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0)
button.addTarget(target, action: action, for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)
return barButtonItem
}
}
Only two Lines of code required for this
Swift 3.0
let closeButtonImage = UIImage(named: "ic_close_white")
navigationItem.rightBarButtonItem = UIBarButtonItem(image: closeButtonImage, style: .plain, target: self, action: #selector(ResetPasswordViewController.barButtonDidTap(_:)))
func barButtonDidTap(_ sender: UIBarButtonItem)
{
}
I am using latest swift (2.1) and the answer (Dharmesh Kheni and jungledev) does not work for me. The image color was off (when setting in IB, it was blue and when setting directly in UIButton, it was black). It turns out I could create the same bar item with the following code:
let barButton = UIBarButtonItem(image: UIImage(named: "menu"), landscapeImagePhone: nil, style: .Done, target: self, action: #selector(revealBackClicked))
self.navigationItem.leftBarButtonItem = barButton
You can use this code for multiple bar button with custom image:
self.navigationItem.leftBarButtonItem = nil
let button = UIButton(type: .custom)
button.setImage(UIImage (named: "ChatTab"), for: .normal)
button.frame = CGRect(x: 0.0, y: 0.0, width: 35.0, height: 35.0)
//button.addTarget(target, action: nil, for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)
let button2 = UIButton(type: .custom)
button2.setImage(UIImage (named: "ActivityTab"), for: .normal)
button2.frame = CGRect(x: 0.0, y: 0.0, width: 35.0, height: 35.0)
//button.addTarget(target, action: nil, for: .touchUpInside)
let barButtonItem2 = UIBarButtonItem(customView: button2)
self.navigationItem.rightBarButtonItems = [barButtonItem, barButtonItem2]
Result will be this:
Initialize barbuttonItem like following:
let pauseButton = UIBarButtonItem(image: UIImage(named: "big"),
style: .plain,
target: self,
action: #selector(PlaybackViewController.pause))
Your problem is because of the way the icon has been made - it doesn't conform to Apple's custom tab bar icon specs:
To design a custom bar icon, follow these guidelines:
Use pure white with appropriate alpha transparency.
Don’t include a drop shadow.
Use antialiasing.
(From the guidelines.)
Something that would be possible looks like this. You can find such icons on most free tab bar icon sites.
Swift 4.
#IBOutlet weak var settingBarBtn: UIBarButtonItem! {
didSet {
let imageSetting = UIImageView(image: UIImage(named: "settings"))
imageSetting.image = imageSetting.image!.withRenderingMode(.alwaysOriginal)
imageSetting.tintColor = UIColor.clear
settingBarBtn.image = imageSetting.image
}
}
SwiftUI
.navigationBarItems modifier takes any view you want:
struct ContentView: View {
var body: some View {
NavigationView {
Text("SwiftUI")
.navigationBarItems(leading:
HStack {
Image(systemName: "trash")
Text("Trash")
}
)
}
}
}
.navigationBarItems(trailing: Image(systemName: "trash") )
.navigationBarItems(leading: Image(systemName: "trash.fill"),
trailing: Image(systemName: "trash")
)
You can use a button for each if you need an action for each of them.
Swift 5+. Smooth solution to add ideal image as you desired dynamic Solution
func rightBarButtonItem(iconNameButton: String, selector: Selector) {
let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
button.setImage(UIImage(named: iconNameButton), for: .normal)
button.addTarget(self, action: selector, for: .touchUpInside)
button.imageView?.contentMode = .scaleAspectFit
let buttonBarButton = UIBarButtonItem(customView: UIView(frame: CGRect(x: 0, y: 0, width: 25, height: 25)))
buttonBarButton.customView?.addSubview(button)
buttonBarButton.customView?.frame = button.frame
self.navigationItem.rightBarButtonItem = buttonBarButton
}
Just choose Original image option when adding an image to assets in Xcode
If your UIBarButtonItem is already allocated like in a storyboard.
(printBtn)
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
btn.setImage(UIImage(named: Constants.ImageName.print)?.withRenderingMode(.alwaysTemplate), for: .normal)
btn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handlePrintPress(tapGesture:))))
printBtn.customView = btn
If you have set up your UIBarButtonItem with an image in the storyboard, one small hack to change the renderingMode is to add the following code to your viewDidLoad(). This way you don't have to resort to adding the entire button and image in code.
if let navButton = self.navigationItem.leftBarButtonItem, let buttonImage = navButton.image {
navButton.image = buttonImage.withRenderingMode(.alwaysOriginal)
}
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Left",
style: .plain,target: self, action: #selector(rightbarButtonAction))
navigationItem.rightBarButtonItem?.image = UIImage(named: "Notification Bell")

How to fit an image in rightbarbuttonitem

I've been trying to put a hamburger button (the three parallel lines) to the right of the titleView in the nav bar, but every time I do, the image I put in covers the entire nav bar and gets rid of the image I have in titleView.
If I select a default image in the storyboard editor it will appear on the right side of the nav bar without any problems, but as soon as I select the hamburger button in the storyboard editor I get the same problem as before. I've tried with multiple different images and I've changed up the code a little bit with no success. Is there a way to resize the image I'm using so it will fit in the nav bar properly or is there just something wrong with my code?
Here is my code from viewController.swift below:
override func viewDidAppear(_ animated: Bool) {
let nav = self.navigationController?.navigationBar
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
imageView.contentMode = .scaleAspectFit
let titleImage = UIImage(named: "logowhitecircle")
imageView.image = titleImage
navigationItem.titleView = imageView
let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
menuButton.contentMode = .scaleAspectFit
let menuImage = UIImage(named: "hamburgericon")
menuButton.setImage(menuImage, for: .normal)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: menuButton)
You need to set image size in the image assets like 3x = 84px, 2x=56px, 1x = 28px,
see the apple document for more info: https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/custom-icons/
let menuButton = UIBarButtonItem(image: UIImage(named: "logowhitecircle"), style: .plain, target: self, action: #selector(menuButtonTapped(_:)))
self.navigationItem.rightBarButtonItem = menuBu
tton
Try Using below code:
let imageBurger = UIImage(named: "hamburgericon")!
let btnLeftMenu = UIButton(type: .system)
btnLeftMenu.bounds = CGRect(x: 10, y: 0, width: imageBurger.size.width, height: imageBurger.size.height)
btnLeftMenu.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
btnLeftMenu.setImage(imageBurger, for: UIControl.State())
btnLeftMenu.setTitle(title, for: .normal)
let leftButton = UIBarButtonItem(customView: btnLeftMenu)
self.navigationItem.leftBarButtonItem = leftButton
Try this module FFBadgedBarButtonItem it's easy to use module, here is the documenataion Link
Below is my code how to implement it!
let image = UIImage(named: "yourImage")
let finalImage = resizeImage(image: image!, newWidth: 30)
navigationItem.rightBarButtonItem = FFBadgedBarButtonItem(image: finalImage, target: self, action: #selector(rightButtonTouched))
And here is the calling function
#objc func rightButtonTouched() {
// what event you need to perfom by clicking on this button
}
You need to create Bridging Header to work with this Obj-C module.
: D
Try this:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//create a new button
let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
//set image for button
button.setImage(UIImage(named: "hamburgericon"), forState: UIControlState.Normal)
//add function for button
button.addTarget(self, action: "customButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
//set frame
button.frame = CGRectMake(0, 0, 40, 40)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
}
//This method will call when you press button.
func customButtonPressed() {
println("button pressed")
}
}

how to set the image position and size of image that inserted in navigation bar?

actually I don't know the correct way how to make an image inside the navigation bar like this, either using navigation controller or by using custom view by myself
I need to insert these 2 image as bar button and image title
so I tried to use navigation controller and insert an image in viewDidLoad like the code below:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// insert image title
let aspectRatio : CGFloat = 0.25
let widthOfImageHeader = view.frame.width * 0.5
let heightOfImageHeader = widthOfImageHeader * aspectRatio
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: widthOfImageHeader, height: heightOfImageHeader))
imageView.contentMode = .scaleAspectFit
let image = UIImage(named: "testImage2")
imageView.image = image
navigationItem.titleView = imageView
// set bar button image
//create a new button
let button = UIButton(type: .custom)
//set image for button
button.setImage(UIImage(named: "hamburgerIcon"), for: .normal)
//set frame
button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.leftBarButtonItem = barButton
}
}
but the result is like the image below:
the position of image title is not exactly in the center for iPhone 5s and bar button seems a little bit off in the right.
and if I assign the image right bar button, using
/
/create a left button
let button = UIButton(type: .custom)
//set image for button
button.setImage(UIImage(named: "hamburgerIcon"), for: .normal)
//set frame
button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.leftBarButtonItem = barButton
//create a right button
let button2 = UIButton(type: .custom)
//set image for button
button2.setImage(UIImage(named: "backButton"), for: .normal)
//set frame
button2.frame = CGRect(x: 0, y: 0, width: 53, height: 51)
let barRightButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barRightButton
the result is even weirder
one of the button dissapears, the hamburger icon that should be on the left, now in the right
it will be far easier if I use custom view, but...is it weird if I use custom view that use like navigation bar? I am new in iOS Developer. Thanks in advance
Okay so here's what I usually do in a project with such kind of requirements (image at the navBar's title, and custom bar button items).
To answer first your question, you can actually do whatever you want.
Have indeed a custom view while having your viewController embedded inside a UINavigationController. But be sure to hide the navBar.
Have a visible navBar and viewContorller embedded in UINavigationController.
The ideal way for me is the latter.
The sample project below was made using my own old framework: https://github.com/glennposadas/gpkit-ios
You can copy any pieces of codes from that framework, modify/rename everything on it, and put in your production project.
If you want the result below, here's how I do it:
import GPKit
import UIKit
class ViewController: UIViewController {
// MARK: - Properties
internal lazy var button_Close: UIButton = {
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "ham"), for: .normal)
button.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: -30, bottom: 0, right: 0)
//button.addTarget(self, action: #selector(hamburger(_:)), for: .touchUpInside)
return button
}()
// MARK: - Functions
// MARK: Overrides
override func viewDidLoad() {
super.viewDidLoad()
GPLog(classSender: self, log: "viewDidLoad!")
// Title View Test: -
let navBarImage = UIImage(named: "ic_logo_navbar")!
self.setNavBarTitleWithFeedback(image: navBarImage, navBarTintColor: .white)
self.makeNavBarColor(color: UIColor.colorWithRGBHex(0x332F39), itemsTintColor: .white)
// Barbutton
let barButton = UIBarButtonItem(customView: self.button_Close)
self.button_Close.frame = CGRect(x: 0, y: 0, width: 55.0, height: 44.0)
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: nil, action: nil)
if #available(iOS 11.0, *) {
negativeSpacer.width = -30
}
self.navigationItem.leftBarButtonItems = [negativeSpacer, barButton]
}
}
extension ViewController: GPTitleViewDelegate {
func gpTitleView(userDidTapTitleView gpTitleView: GPTitleView) {
GPLog(classSender: self, log: "userDidTapTitleView🌈")
}
func gpTitleView(userDidFinishLongPress gpTitleView: GPTitleView) {
GPLog(classSender: self, log: "userDidFinishLongPress🌺")
}
}
Result:
I don't have your hex color, so it looks ugly.
I hope thish elps.

Trying to call a navigation bar function in another class pragmatically

I created a navigation bar which I'm trying to call in another view controller. I set it up by calling the methods which I separated into left, center and right buttons. In my other controller I call the navbarcontroller and try and call the method for which i setup the navigation toolbar. Nothing happens, however there is no crash.
import UIKit
class NavBarController : UIViewController{
var screenSize: CGRect!
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBarItems()
setupToolBarItems()
self.navigationController?.isToolbarHidden = false
self.view!.backgroundColor = .white
}
and my method for the navigation bar is this
func setupNavigationBarItems() {
setupCenterNavButton()
setupLeftNavButton()
setupRightNavButton()
}
func showCalendarController() {
let navController = CalendarController()
self.present(navController, animated: true, completion: nil)
} //connect bottom bar buttons to controller
func showEventsController() {
let navController = EventsController()
self.present(navController, animated: true, completion: nil)
} //connect bottom bar buttons to controller
func setupNavigationBarItems() {
setupCenterNavButton()
setupLeftNavButton()
setupRightNavButton()
} // top bar button setup
private func setupCenterNavButton() {
let buttonFrame = UIView(frame: CGRect(x: 0, y: 0, width: 165,
height: 20))
mainFeedButton.frame = CGRect(x: 0,y: 0, width: 80,height: 20) as
CGRect
mainFeedButton.backgroundColor = UIColor.blue
peekFeedButton.frame = CGRect(x: 85,y: 0, width: 80,height: 20) as
CGRect
peekFeedButton.backgroundColor = UIColor.blue
buttonFrame.addSubview(mainFeedButton)
buttonFrame.addSubview(peekFeedButton)
navigationItem.titleView = buttonFrame
} //center bar buttons / action setup
private func setupLeftNavButton() {
navigationItem.leftBarButtonItem = UIBarButtonItem(customView:
favoriteButton)
}// left bar buttons / action setup
private func setupRightNavButton() {
navigationItem.rightBarButtonItem = UIBarButtonItem(customView:
moreButton)
} //right bar buttons / action setup
lazy var mainFeedButton: UIButton! = {
let button = UIButton(type: .custom) // button type
button.setTitle("Main",for: .normal) //button title
button.sizeToFit() // size button to fit the title
var frame = button.frame //create frame to manipulate the body
button.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
button.addTarget(self, action:
#selector(self.showMainFeedController),
for: .touchUpInside)
return button
}() //mainFeed button connected to Feed Controller
lazy var peekFeedButton: UIButton! = {
let button = UIButton(type: .custom) //button type
button.setTitle("Spy",for: .normal) //button title
button.sizeToFit() // size button to fit the title
var frame = button.frame //create frame to manipulate the body
button.frame = CGRect(x: 20, y: 0, width: 100, height: 40)
button.addTarget(self, action:
#selector(self.showSpyFeedController),
for: .touchUpInside)
return button
}()//peekFeed button frame and action setup
lazy var favoriteButton: UIButton! = {
let button = UIButton(type: .system) //default button with blue
text
button.setImage(#imageLiteral(resourceName:
"star").withRenderingMode(.alwaysOriginal), for: .normal)
button.contentMode = .scaleAspectFit
button.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
button.addTarget(self, action: #selector(favoriteButton_tapped),
for: .touchUpInside)
return button
}() //favorites button frame and action setup
lazy var moreButton: UIButton! = {
let button = UIButton(type: .system) //default button with blue
text
button.setImage(#imageLiteral(resourceName:
"more").withRenderingMode(.alwaysOriginal), for: .normal)
button.contentMode = .scaleAspectFit
button.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
button.addTarget(self, action: #selector(moreButton_tapped),
for: .touchUpInside)
return button
}() //more button frame and action setup
func showMainFeedController() {
let navController = MainFeedController()
self.present(navController, animated: true, completion: nil)
} //mainFeed button connected to Feed Controller
func showSpyFeedController() {
let navController = SpyFeedController()
self.present(navController, animated: true, completion: nil)
}//peekFeed button connected to SpyFeedController
func favoriteButton_tapped(sender: UIButton) {
print("You touched this!")
}
func moreButton_tapped(sender: UIButton) {
print("You touched this!")
}
}
I then try and call the function by setupNavigationBarItems() like this
import UIKit
class EventsController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
let navbar = NavBarController()
navbar.setupNavigationBarItems()
self.navigationController?.isToolbarHidden = false
self.view.backgroundColor = .white
}
}
I'm not sure if this a valid way. I'm still kinda new to all of this.
It's not clear what you expect to happen, but here's what does happen:
let navbar = NavBarController()
A completely new NavBarController object is created.
navbar.setupNavigationBarItems()
That NavBarController object's setupNavigationBarItems is called.
self.navigationController?.isToolbarHidden = false
self.view.backgroundColor = .white
Your code comes to an end. navbar was a local variable, so the NavBarController object vanishes in a puff of smoke. The end. This object was created and configured to no purpose.
I remember my first month in iOS way back 2015 :D, didn't have any knowledge in OOP, I didn't know too how to pass a data to another screen or class.
Anyways, you DO NOT create a new instance of your NavBarController class in your EventsController. If you want to talk to your NavBarController from your EventsController, then you will need a reference that is currently alive. You can also use delegate (search for that later).
So before you show or present your EventsController from your NavBarController, pass your current NavBarController instance to the next screen which is EventsController. BUT FIRST, you need to declare a variable in your EventsController, correct? :)
Declare a variable with a type of NavBarController inside your EventsController class, like so:
var navBarController: NavBarController!
Then in this piece of code of yours, pass your self (the NavBarController instance) to the EventsController class before showing or presenting, take note that you mistakenly gave a wrong name to your EventsController new instance, so I renamed it:
func showEventsController() {
let eventsController = EventsController()
eventsController.navBarController = self // THIS :)
self.present(eventsController, animated: true, completion: nil)
}
Lastly, instead of this:
let navbar = NavBarController()
navbar.setupNavigationBarItems()
Make use of your declared variable, like so:
self.navBarController.navbar.setupNavigationBarItems()
Hope this helps! :)

Why is UIView removed from heirarchy after presenting view controller?

Ok I just ran into something bizarre. I've got my app controller dependency injecting a view (header) into a view controller. That view controller presents another view controller modally and dependency injects it's own header for the presenting view controller to use. But when its presented the header from the first controller disappears.
The property is still set but it's been removed from the view hierarchy.
I've reproduced this issue in fresh singleview project:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
let button = UIButton(frame: CGRect(x: 0, y: 20, width: 100, height: 50))
button.setTitle("Click Me!", for: .normal)
button.addTarget(self, action: #selector(self.segue), for: .touchUpInside)
button.backgroundColor = .black
button.setTitleColor(.lightGray, for: .normal)
self.view.addSubview(button)
}
func segue() {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = .lightGray
let firstVC = FirstViewController()
firstVC.sharedView = view
present(firstVC, animated: false)
}
}
class FirstViewController: UIViewController {
var sharedView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.view.addSubview(self.sharedView)
let button = UIButton(frame: CGRect(x: 0, y: 200, width: 100, height: 50))
button.setTitle("Click Me!", for: .normal)
button.addTarget(self, action: #selector(self.segue), for: .touchUpInside)
button.backgroundColor = .black
button.setTitleColor(.lightGray, for: .normal)
self.view.addSubview(button)
}
func segue() {
let secondVC = SecondViewController()
secondVC.sharedView = self.sharedView
present(secondVC, animated: true)
}
}
class SecondViewController: UIViewController {
var sharedView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.view.addSubview(self.sharedView)
let button = UIButton(frame: CGRect(x: 0, y: 200, width: 100, height: 50))
button.setTitle("Click Me!", for: .normal)
button.addTarget(self, action: #selector(self.segue), for: .touchUpInside)
button.backgroundColor = .black
button.setTitleColor(.lightGray, for: .normal)
self.view.addSubview(button)
}
func segue() {
self.dismiss(animated: true)
}
}
Can someone explain what's going on here? Why does the sharedView disappear from the FirstViewController?
At the doc of -addSubview(_:):
Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous
superview before making the receiver its new superview.
That should explain your issue.
I'd suggest instead that you create a method that generate a headerView (a new one each time) according to your customization style.
If you really want to "copy" the view, you can check that answer. Since UIView is not NSCopying Compliant, their trick is to "archive/encode" it since it's NSCoding compliant, copy that archive, and "unarchive/decode" the copy of it.

Resources