Xcode Swift: Cannot close popup Image - ios

I created a ViewController that displays three images and other info via JSON parsing through three separate UIImageViews. When you click any of the images, it takes you to another ViewController that pop-ups a UIScrollView in the background, one UIImageView which is linked to all three images and a Button that would close the pop-up ViewController and bring it back to the previous one. Here is a screenshot. The problem I am having is that I added this code:
func removeZoom()
{
UIView.animateWithDuration(0.25, animations: {
self.view.transform = CGAffineTransformMakeScale(1.3, 1.3)
self.view.alpha = 0.0;
}, completion:{(finished : Bool) in
if (finished)
{
self.view.removeFromSuperview()
}
});
}
#IBAction func closeZoom(sender: AnyObject) {
self.navigationController?.popToRootViewControllerAnimated(true)
}
And when I try to click on the close button, nothing happens. Don't know what I am missing. Any guidance would be helpful.
Here i'll put the code for both controllers:
JnsDetail.swift
import Foundation
import UIKit
class JnsDetail: UIViewController {
#IBOutlet var tituloLabel : UILabel!
#IBOutlet var marcaLabel : UILabel!
#IBOutlet var colorLabel : UILabel!
#IBOutlet var tipoLabel : UILabel!
#IBOutlet var refLabel : UILabel!
#IBOutlet var imageView : UIImageView!
#IBOutlet var imageView2 : UIImageView!
#IBOutlet var imageView3 : UIImageView!
#IBOutlet var backbutton : UIButton!
var jsonextrct : JsonExtrct!
var photos : [String]!
var transitionOperator = TransitionOperator()
override func viewDidLoad() {
super.viewDidLoad()
//titulo = jsonextrct.titulo
tituloLabel.font = UIFont(name: mTheme.fontName, size: 21)
tituloLabel.textColor = UIColor.blackColor()
tituloLabel.text = jsonextrct.titulo
//marca = jsonextrct.marca
marcaLabel.font = UIFont(name: mTheme.fontName, size: 21)
marcaLabel.textColor = UIColor.blackColor()
marcaLabel.text = jsonextrct.marca
//color = jsonextrct.color
colorLabel.font = UIFont(name: mTheme.fontName, size: 21)
colorLabel.textColor = UIColor.blackColor()
colorLabel.text = jsonextrct.color
//tipo = jsonextrct.tipo
tipoLabel.font = UIFont(name: mTheme.fontName, size: 21)
tipoLabel.textColor = UIColor.blackColor()
tipoLabel.text = jsonextrct.tipo
//ref = jsonextrct.ref
refLabel.font = UIFont(name: mTheme.fontName, size: 21)
refLabel.textColor = UIColor.blackColor()
refLabel.text = "\(jsonextrct.ref)"
if let imageData = jsonextrct.imageData {
imageView.image = UIImage(data: imageData)
}else{
Utils.asyncLoadJsonImage(jsonextrct, imageView: imageView)
}
//topImageViewHeightConstraint.constant = 240
imageView.layer.borderColor = UIColor(white: 0.2, alpha: 1.0).CGColor
imageView.layer.borderWidth = 0.5
if let imageData2 = jsonextrct.imageData2 {
imageView2.image = UIImage(data: imageData2)
}else{
Utils.asyncLoadJsonImage(jsonextrct, imageView2: imageView2)
}
imageView2.layer.borderColor = UIColor(white: 0.2, alpha: 1.0).CGColor
imageView2.layer.borderWidth = 0.5
if let imageData3 = jsonextrct.imageData3 {
imageView3.image = UIImage(data: imageData3)
}else{
Utils.asyncLoadJsonImage(jsonextrct, imageView3: imageView3)
}
imageView3.layer.borderColor = UIColor(white: 0.2, alpha: 1.0).CGColor
imageView3.layer.borderWidth = 0.5
var tapGestureZoom = UITapGestureRecognizer(target: self, action: "zoomJns:")
tapGestureZoom.numberOfTapsRequired = 1
tapGestureZoom.numberOfTouchesRequired = 1
imageView.userInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureZoom)
var tapGestureZoom2 = UITapGestureRecognizer(target: self, action: "zoomJns2:")
tapGestureZoom2.numberOfTapsRequired = 1
tapGestureZoom2.numberOfTouchesRequired = 1
imageView2.userInteractionEnabled = true
imageView2.addGestureRecognizer(tapGestureZoom2)
var tapGestureZoom3 = UITapGestureRecognizer(target: self, action: "zoomJns3:")
tapGestureZoom3.numberOfTapsRequired = 1
tapGestureZoom3.numberOfTouchesRequired = 1
imageView3.userInteractionEnabled = true
imageView3.addGestureRecognizer(tapGestureZoom3)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.Default
}
func backTapped(sender: AnyObject?){
dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func zoomJns(sender: AnyObject?){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("JnsZoomController") as! JnsZoomController
self.modalPresentationStyle = UIModalPresentationStyle.Custom
controller.transitioningDelegate = transitionOperator
controller.jsonextrct = jsonextrct
presentViewController(controller, animated: true, completion: nil)
}
#IBAction func zoomJns2(sender: AnyObject?){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("JnsZoomController") as! JnsZoomController
self.modalPresentationStyle = UIModalPresentationStyle.Custom
controller.transitioningDelegate = transitionOperator
controller.jsonextrct = jsonextrct
presentViewController(controller, animated: true, completion: nil)
}
#IBAction func zoomJns3(sender: AnyObject?){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("JnsZoomController") as! JnsZoomController
self.modalPresentationStyle = UIModalPresentationStyle.Custom
controller.transitioningDelegate = transitionOperator
controller.jsonextrct = jsonextrct
presentViewController(controller, animated: true, completion: nil)
}
}
JnsZoomController.swift
import Foundation
import UIKit
class JnsZoomController : UIViewController {
#IBOutlet var scrollView : UIScrollView!
#IBOutlet var jnsImageView : UIImageView!
#IBOutlet var jnsImageView2 : UIImageView!
#IBOutlet var jnsImageView3 : UIImageView!
var jsonextrct : JsonExtrct!
override func viewDidLoad() {
super.viewDidLoad()
if let imageData = jsonextrct.imageData {
let image = UIImage(data: imageData)
jnsImageView.image = UIImage(data: imageData)
//jnsImageView.bounds = CGRectMake(0, 0, image?.size.width, image?.size.height);
}
if let imageData2 = jsonextrct.imageData2 {
let image2 = UIImage(data: imageData2)
jnsImageView2.image = UIImage(data: imageData2)
//jnsImageView2.bounds = CGRectMake(0, 0, image?.size.width, image?.size.height);
}
if let imageData3 = jsonextrct.imageData3 {
let image3 = UIImage(data: imageData3)
jnsImageView3.image = UIImage(data: imageData3)
//jnsImageView3.bounds = CGRectMake(0, 0, image?.size.width, image?.size.height);
}
scrollView.contentSize = jnsImageView.frame.size
scrollView.contentSize = jnsImageView2.frame.size
scrollView.contentSize = jnsImageView3.frame.size
}
func removeZoom()
{
UIView.animateWithDuration(0.25, animations: {
self.view.transform = CGAffineTransformMakeScale(1.3, 1.3)
self.view.alpha = 0.0;
}, completion:{(finished : Bool) in
if (finished)
{
self.view.removeFromSuperview()
}
});
}
#IBAction func closeZoom(sender: AnyObject) {
self.navigationController?.popToRootViewControllerAnimated(true)
}
}

Here's the problem as I see it, if you are "popping" to root view controller this means that you must have PUSHED a view controller onto the navigation controller's stack and I don't see you pushing anything onto a navigation stack. Unless of course for some reason Apple decided to kill off Pushing view controllers, but I doubt this is the case. So, there's another problem with what I'm seeing in your code. You are PRESENTING view controllers by just presenting a view controller, I don't see where you are presenting a view controller by using a navigation controller to present the view controller SOOO, if you call
self.navigationController?.popToRootViewControllerAnimated(true)
then there's nothing on the stack that the navigation controller is to remove from the stack since you presented the viewcontroller modally over another viewcontroller without presenting the modal in the view controller's navigation controller.
Solution, maybe, but this isn't 100% becuase I don't have your code in front of me.
change this:
self.navigationController?.popToRootViewControllerAnimated(true)
to something like this
self.dismissViewControllerAnimated(animated: true, completion:nil)
I don't do swift so my solution is pseudo code, feel free to add the questions marks and what not that Apple decided has value for some reason.
You could also just change your presentations to this:
self.navigationController?.presentViewController(controller, animated: true, completion: nil)
Again, the above is psuedo code but I think I place the question mark in just the right spot for so that it does what it's suppose to do
Also, you can refer to this, although Apple doesn't really do a very thoroughly job of telling you how an advanced navigaiton stack works:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UINavigationController_Class/#//apple_ref/occ/instm/UINavigationController/pushViewController:animated:
Sometimes you will need to have maybe 4-10 navigation controllers running at one time, so make sure you understand how they interact with view controllers and make sure you understand what POPs, PUSHes, and PRESENTs do. And good luck, have a good day.

In the closeZoom I think you should use only
#IBAction func closeZoom(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
Because you presented that View Controller, that popToRootViewControllerAnimated(true) is used when you push it

Related

How to change label text of a label in a popover view controller when pressing a button in the main view?

I'm relatively new to Swift. I have a main view controller, ViewControllerMain, and a popover view controller, PopUpVC, which only has a label. I have a function, infoClicked that displays the popover with another function (showPopover) when the info button is clicked. When I click the button, I want to change the label text of the popover. However, with the current code, the label always displays "Default".
Here is my code:
class ViewControllerMain: UIViewController, UIPopoverPresentationControllerDelegate, GetTimesUsed {
let tipController: PopUpVC = PopUpVC().self
#IBAction func infoClicked(_ sender: UIButton) {
tipController.tipText = "Success"
showPopover()
}
func showPopover() {
let myViewController = storyboard?.instantiateViewController(withIdentifier: "popupController")
myViewController?.preferredContentSize = CGSize(width: 350, height: 200)
myViewController?.modalPresentationStyle = .popover
let popOver = myViewController?.popoverPresentationController
popOver?.delegate = self
UIView.animate(withDuration: 1, animations: {
self.GifView.alpha = 0.7
})
DispatchQueue.main.asyncAfter(deadline: .now() + 0.45) {
UIView.animate(withDuration: 0.5, animations: {
self.present(myViewController!, animated: true, completion: nil)
})
}
popOver?.permittedArrowDirections = .down
popOver?.sourceView = self.view
var passthroughViews: [AnyObject]?
passthroughViews = [infoButton]
myViewController?.popoverPresentationController?.passthroughViews = (NSMutableArray(array: passthroughViews!) as! [UIView])
popOver?.sourceRect = infoButton.frame
}
}
class PopUpVC: UIViewController {
#IBOutlet weak var tip: UILabel!
var tipText: String = "Default"
override func viewDidLoad() {
super.viewDidLoad()
tip.text = tipText
// Do any additional setup after loading the view.
}
}
Thank you for your help.
As mentioned in comments, you seem to be instantiating the popup controller 2 times, so try it like this in your showPopOver code:
let myViewController = storyboard?.instantiateViewController(withIdentifier: "popupController") as! PopUpVC
myViewController.preferredContentSize = CGSize(width: 350, height: 200)
myViewController.modalPresentationStyle = .popover
myViewController.tipText = '' //set to what ever

How to center custom tabbar item on iPhone X

I have an app where I created a custom tabbar item in a UITabbarController, that someone can press to take a picture, and it looks like it does below.
That is exactly what I want, the problem is that when I test it on an iPhone X, the tabbar item for the camera looks lower then I would like, for example:
I have tried a couple of things to fix this, such as fixing the height of the tabbar in the viewDidLayoutSubviews(), but it messed with the tabbar on the iPhone 8. I also made sure that the "Use Safe Area Layout Guides" is selected, but it still doesn't work.
I also tried to change the frame of the tabbar item, but that doesn't work either.
This is the code that I used for the custom tabbar Controller:
import UIKit
class OtherTabController: UITabBarController, UITabBarControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
setupBtn()
// Do any additional setup after loading the view.
}
func setupBtn() {
let centerBtn = UIButton(frame: CGRect(x: 0, y: 10, width: 45, height: 45))
var centerBtnFrame = centerBtn.frame
centerBtnFrame.origin.y = (view.bounds.height - centerBtnFrame.height) - 2
centerBtnFrame.origin.x = view.bounds.width/2 - centerBtnFrame.size.width/2
centerBtn.frame = centerBtnFrame
centerBtn.layer.cornerRadius = 35
view.addSubview(centerBtn)
let centerImg = UIImage(named: "Other")
centerBtn.setBackgroundImage(centerImg, for: .normal)
centerBtn.addTarget(self, action: #selector(centerBtnAction(sender:)), for: .touchUpInside)
view.layoutIfNeeded()
}
#objc private func centerBtnAction(sender: UIButton) {
print("Camera")
cameraAction()
}
func cameraAction() {
let alertController = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
let takePhotoAction = UIAlertAction(title: "Take a Photo", style: .default, handler: nil)
alertController.addAction(takePhotoAction)
let selectFromAlbumAction = UIAlertAction(title: "Select from Album", style: .default, handler: nil)
alertController.addAction(selectFromAlbumAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
//OtherTabController?.present(alertController, animated: true, completion: nil)
}
}
If there is anything else I could help with, please ask. Thank you
EDIT:
I tried to make the y view the same as the super view but all it did was move the button to the top of the screen.
var centerBtnFrame = centerBtn.frame
centerBtnFrame.origin.y = view.bounds.minY //Make centerBtn' top equal to that of view's
centerBtnFrame.origin.x = view.bounds.width/2 - centerBtnFrame.size.width/2
centerBtn.frame = centerBtnFrame
If you need any more info, please ask. Thank you
Edit:
With the help of #Revanth Kausikan, I decided to create a custom tabbar with a view and a few buttons. It works very well in my opinion. It looks a little rough around the edges, but this is just a test for now.
Here is the code for the view:
import UIKit
class ItemScene: UIViewController {
#IBOutlet var customTab: UIView!
#IBOutlet weak var cameraBtn: UIButton!
#IBOutlet weak var twoBtn: UIButton!
#IBOutlet weak var oneBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func cameraBtnPressed(_ sender: Any) {
print("Camera")
}
#IBAction func twoBtnPressed(_ sender: Any) {
self.performSegue(withIdentifier: "segue", sender: nil)
print("Two")
}
#IBAction func oneBtnPressed(_ sender: Any) {
print("One")
}
}
this is the code for the second ViewController:
import UIKit
class TestingViewController: UIViewController {
#IBOutlet weak var cameraBtn: UIButton!
#IBOutlet weak var oneBtn: UIButton!
#IBOutlet weak var twoBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func cameraBtnPressed(_ sender: Any) {
print("Camera")
}
#IBAction func twoBtnPressed(_ sender: Any) {
print("Two")
}
#IBAction func oneBtnPressed(_ sender: Any) {
performSegueToReturnBack()
print("One")
}
}
extension UIViewController {
func performSegueToReturnBack() {
if let nav = self.navigationController {
nav.popViewController(animated: true)
} else {
self.dismiss(animated: true, completion: nil)
}
}
}
If anyone has anything else to add it would be greatly appreciated. Thank you
The Y point of button frame must be the same as that of it's super view (i.e. tab bar here).
If you've not created an outlet for the tab bar, first do so.
Ctrl (or right) click and drag from your tab bar in the storyboard to its associated view controller, to create an outlet. (assume that I'm naming it as tabBar)
now try this:
var centerBtnFrame = centerBtn.frame
let tabBarFrame = self.convert(tabBar.frame, to: view)
centerBtnFrame.origin.y = tabBarFrame.minY //Make centerBtn' top equal to that of tabBar's
centerBtnFrame.origin.x = view.bounds.width/2 - centerBtnFrame.size.width/2
centerBtn.frame = centerBtnFrame
Alternatively, you can try this:
var centerBtnFrame = centerBtn.frame
centerBtnFrame.origin.y = view.height - tabBar.height //This is the same logic as you've used for fixing x value of centerBtnFrame.
centerBtnFrame.origin.x = view.bounds.width/2 - centerBtnFrame.size.width/2
centerBtn.frame = centerBtnFrame
Yet another approach is to go back to the constraints, and make sure the elements and the base view are within the safe area.
If my guess is right (since you've not provided details about the constraints in the question), you've set the base view (the view that is in the bottom/base, holding all other elements on it) to fit itself with the entire view are of the view controller. Consider changing it to fit itself within the safe area.
Let me know the results.
EDIT
My opinion on your new attempt: It's really good, and I see that you are now able to customize it a lot more.
To improve it, you can try these:
Here, there are three views that are clickable in nature. we can use this to increase the interactive area as per our wish, to provide a natural experience for the user.
Here are it's constraints:
Other than these suggestions, I don't think I need to provide any. Your method is self sufficient for your implementation idea.
:)
Try this code working 100% ...
Declare the button
var menuButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
setupMiddleButton()
}
//create the method
func setupMiddleButton(flag:String) {
menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 60))
var menuButtonFrame = menuButton.frame
menuButtonFrame.origin.y = tabBar.bounds.height - menuButtonFrame.height
menuButtonFrame.origin.x = tabBar.bounds.width/2 - menuButtonFrame.size.width/2
menuButton.frame = menuButtonFrame
menuButton.backgroundColor = UIColor.red
menuButton.layer.borderColor = UIColor.black.cgColor
menuButton.layer.borderWidth = 1
tabBar.addSubview(menuButton)
menuButton.layer.cornerRadius = menuButtonFrame.height/2
menuButton.setImage(UIImage(named: "Homenormal"), for: .normal)
menuButton.addTarget(self, action: #selector(menuButtonAction(sender:)), for: .touchUpInside)
}
//button methods inside add background colour
#objc private func menuButtonAction(sender: UIButton) {
menuButton.backgroundColor = UIColor.red
selectedIndex = 2
print("menuButtonActio=\(sender.tag)")
}
//next Tabbar didselect
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
let Selected_index = tabBar.items?.lastIndex(of: item)
print("selectedIndex123=\(Selected_index)")
if Selected_index == 0 {
menuButton.backgroundColor = UIColor.darkGray
menuButton.layer.borderColor = UIColor.black.cgColor
}
else if Selected_index == 1 {
menuButton.backgroundColor = UIColor.darkGray
menuButton.layer.borderColor = UIColor.black.cgColor
}
else if Selected_index == 2 {
menuButton.backgroundColor = UIColor.red
menuButton.layer.borderColor = UIColor.black.cgColor
}
else if Selected_index == 3 {
menuButton.backgroundColor = UIColor.darkGray
menuButton.layer.borderColor = UIColor.black.cgColor
}
else if Selected_index == 4 {
menuButton.backgroundColor = UIColor.darkGray
menuButton.layer.borderColor = UIColor.black.cgColor
}
}

issue while using sambag time picker

i am using sambag time picker controller and i am set time on button on method of sambag picker but issue is that i have multiple buttons in one view controller so i did this for every but on set time method at the time of set button all buttons title are change what i want is that only change value of button which i pressed
here i will show you what i tried i will show you with my code
import UIKit
class ManageHoursViewController: UIViewController {
var theme: SambagTheme = .light
var result : String!
#IBOutlet weak var btnMonStartTime: UIButton!
#IBOutlet weak var btnMonEndTime: UIButton!
#IBOutlet weak var btnMonOff: UIButton!
#IBOutlet weak var btnMonOn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
round()
let hh2 = (Calendar.current.component(.hour, from: Date()))
let mm2 = (Calendar.current.component(.minute, from: Date()))
print(hh2)
print(mm2)
let dateTime = "\(hh2) : \(mm2)"
btnMonStartTime.setTitle("\(dateTime)", for: .normal)
btnMonEndTime.setTitle("\(dateTime)", for: .normal)
// Do any additional setup after loading the view.
}
func round(){
btnMonOff.isHidden = true
btnMonStartTime.layer.cornerRadius = btnMonStartTime.frame.height / 2
btnMonStartTime.layer.shadowColor = UIColor(red: 154/255, green: 154/255, blue: 154/255, alpha: 1).cgColor
btnMonStartTime.layer.shadowOffset = CGSize(width: 0, height: 1)
btnMonStartTime.layer.shadowOpacity = 1.0
btnMonStartTime.layer.shadowRadius = 2.0
btnMonStartTime.layer.masksToBounds = false
btnMonEndTime.layer.cornerRadius = btnMonEndTime.frame.height / 2
btnMonEndTime.layer.shadowColor = UIColor(red: 154/255, green: 154/255, blue: 154/255, alpha: 1).cgColor
btnMonEndTime.layer.shadowOffset = CGSize(width: 0, height: 1)
btnMonEndTime.layer.shadowOpacity = 1.0
btnMonEndTime.layer.shadowRadius = 2.0
btnMonEndTime.layer.masksToBounds = false
}
#IBAction func btnMonStartTimeTapped(_ sender: UIButton) {
let vc = SambagTimePickerViewController()
vc.theme = theme
vc.delegate = self
present(vc, animated: true, completion: nil)
}
#IBAction func btnMonEndTimeTapped(_ sender: UIButton) {
let vc = SambagTimePickerViewController()
vc.theme = theme
vc.delegate = self
present(vc, animated: true, completion: nil)
}
}
extension ManageHoursViewController : SambagTimePickerViewControllerDelegate {
func sambagTimePickerDidSet(_ viewController: SambagTimePickerViewController, result: SambagTimePickerResult) {
self.result = "\(result)"
print(self.result)
btnMonStartTime.setTitle(self.result, for: .normal)
btnMonEndTime.setTitle(self.result, for: .normal)
viewController.dismiss(animated: true, completion: nil)
}
func sambagTimePickerDidCancel(_ viewController: SambagTimePickerViewController) {
viewController.dismiss(animated: true, completion: nil)
}
}
i want like when monday start time button press then and i select time form picker then only monday start time button value change at now all button value changed
You can create a var to track last clicked one
var lastBu: UIButton!
#IBAction func btnMonStartTimeTapped(_ sender: UIButton) {
let vc = SambagTimePickerViewController()
vc.theme = theme
vc.delegate = self
lastBu = sender
present(vc, animated: true, completion: nil)
}
#IBAction func btnMonEndTimeTapped(_ sender: UIButton) {
let vc = SambagTimePickerViewController()
vc.theme = theme
vc.delegate = self
lastBu = sender
present(vc, animated: true, completion: nil)
}

IOS UISegmentedControl doesn't not display in ios 10

I'm a beginner in IOS. I'm developping a Swift app and I am using a UISegmentedControl. It displays well in ios 11, but when I run my app on a IOS 10 device, the segmented control is not showing. Does anyone know why ?
Is the segmented control only available in IOS 11 ?
Here are the screenshots of my app (sorry I can't post images yet) :
IOS 11
IOS10
Here is my SegmentedViewController.swift :
import UIKit
import MMDrawerController
class SegmentedViewController: UIViewController {
#IBOutlet weak var viewContainer: UIView!
var segmentedController: UISegmentedControl!
var floorRequest:Int = 0
var segmentedControlIndex:Int = 0
lazy var travelViewController: TravelViewController = {
var viewController = self.initTravelViewController()
return viewController
}()
lazy var nearbyViewController: NearbyTableViewController = {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
var viewController = storyboard.instantiateViewController(withIdentifier: "NearbyTableViewController") as! NearbyTableViewController
self.addViewControllerAsChildViewController(childViewController: viewController)
return viewController
}()
var views: [UIView]!
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
func initTravelViewController() -> TravelViewController {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let viewController = storyboard.instantiateViewController(withIdentifier: "TravelViewController") as! TravelViewController
viewController.floorRequest = floorRequest
self.addViewControllerAsChildViewController(childViewController: viewController)
return viewController
}
override func viewDidLoad() {
super.viewDidLoad()
segmentedController = UISegmentedControl()
navigationItem.titleView = segmentedController
self.title = "TAB_BAR_MAP".localized()
}
override func viewWillAppear(_ animated: Bool) {
self.tabBarController?.navigationItem.title = "MENU_SECTION_TRAVEL".localized().uppercased()
// Navigation Bar
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName: UIFont(name: "Lato-Bold", size: 18)!]
self.navigationController?.navigationBar.tintColor = .white
self.navigationController?.navigationBar.barTintColor = appDelegate.colorAqaDark
self.navigationController?.navigationBar.isTranslucent = false
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
if (self.navigationController?.viewControllers.count)! < 2 {
let buttonLeft: UIButton = appDelegate.aqaBarButton(image: #imageLiteral(resourceName: "IconWhiteMenu"))
buttonLeft.addTarget(self, action: #selector(toggleMenu), for: .touchUpInside)
buttonLeft.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25)
let buttonMenu = UIBarButtonItem(customView: buttonLeft)
self.navigationItem.setLeftBarButton(buttonMenu, animated: false);
}
setupView()
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func toggleMenu() {
appDelegate.mainContainer!.toggle(MMDrawerSide.left, animated: true, completion: nil)
}
private func setupView(){
setupSegmentedControl()
updateView()
}
private func updateView(){
travelViewController.view.isHidden = !(segmentedController.selectedSegmentIndex == 0)
nearbyViewController.view.isHidden = (segmentedController.selectedSegmentIndex == 0)
segmentedControlIndex = segmentedController.selectedSegmentIndex
}
private func setupSegmentedControl(){
segmentedController.removeAllSegments()
segmentedController.insertSegment(withTitle: "TAB_BAR_MAP".localized(), at: 0, animated: false)
segmentedController.insertSegment(withTitle: "TAB_BAR_NEARBY".localized(), at: 1, animated: false)
segmentedController.addTarget(self, action: #selector(selectionDidChange(sender:)), for: .valueChanged)
segmentedController.selectedSegmentIndex = segmentedControlIndex
}
func selectionDidChange(sender: UISegmentedControl){
updateView()
}
private func addViewControllerAsChildViewController(childViewController: UIViewController){
addChildViewController(childViewController)
view.addSubview(childViewController.view)
childViewController.view.frame = view.bounds
childViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
childViewController.didMove(toParentViewController: self)
}
}
The problem is that you are not giving the segmented control any size. In iOS 11 the title view is sized internally by autolayout, but not in iOS 10 or before. So you end up with a segmented control of zero size.

Custom Alert (UIAlertView) with swift

How can i create a custom alert with Swift? I try translating a guide from Objective c but loads a full screen layout
for do it easy i can load a new layout with the transparent background i try this:
listaalertviewcontroller.view.backgroundColor = UIColor.clearColor()
let purple = UIColor.purpleColor() // 1.0 alpha
let semi = purple.colorWithAlphaComponent(0.5)
listaalertviewcontroller.view.backgroundColor = semi
presentingViewController.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
self.presentViewController(listaalertviewcontroller, animated: true, completion: nil)
in the animation it's transparent but when the animation ends it's opaque... and i turn off opaque option in the view... what i'm doing wrong?
Code tested in Swift 5 and Xcode 10
How to make your own custom Alert
I was wanting to do something similar. First of all, UIAlertView is deprecated in favor of UIAlertController. See this answer for the standard way to display an alert:
How would I create a UIAlertView in Swift?
And both UIAlertView and UIAlertController do not really allow much customization. One option is to use some third party code. However, I discovered that it isn't that difficult to create your own Alert by displaying another view controller modaly.
The example here is just a proof-of-concept. You can design your alert any way you want.
Storyboard
You should have two View Controllers. Your second view controller will be your alert. Set the class name to AlertViewContoller and the Storyboard ID to alert. (Both of these are names that we defined ourselves in the code below, nothing special about them. You can add the code first if you want. It might actually be easier if you add the code first.)
Set the background color for the root view (in your Alert View Controller) to clear (or translucent black is nice for an alert). Add another UIView and center it with constraints. Use that as your alert background and put whatever you want inside. For my example, I added a UIButton.
Code
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBAction func showAlertButtonTapped(_ sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myAlert = storyboard.instantiateViewController(withIdentifier: "alert")
myAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
myAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
self.present(myAlert, animated: true, completion: nil)
}
}
AlertViewController.swift
import UIKit
class AlertViewController: UIViewController {
#IBAction func dismissButtonTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
Don't forget to hook up the outlets.
You can add an onTouchUp event listener to the background view to dismiss the popup when the user clicks outside of it.
That's it. You should be able to make any sort of alert that you can imagine now. No need for third party code.
Here is another custom alert I made. Still ugly, but it shows more things you can do.
Other options
Sometimes there is no need to reinvent the wheel, though. I'm impressed with the third party project SDCAlertView (MIT license). It is written in Swift but you can use it with Objective-C projects as well. It offers a wide range of customability.
Here is the Swift 3 code. Thanks a lot #Suragch for the awesome approach to create a custom AlertView.
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBAction func showAlertButtonTapped(sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myAlert = storyboard.instantiateViewController(withIdentifier: "storyboardID")
myAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
myAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
self.present(myAlert, animated: true, completion: nil)
}
AlertViewController.swift
import UIKit
class AlertViewController: UIViewController {
#IBAction func dismissButtonTapped(sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
To make it a little more interesting or to make the default effect in iOS, you could add either a VisualEffectView or change the color of the main UIView to a dark color and set its alpha to 70%. I prefer the second approach since the blur effect is not as smooth as the one with the view with 70 alpha.
Effect with VisualEffectView:
Effect using a UIView with 70 Alpha:
Nowadays, an alert is merely a simple presented view controller. You can write a presented view controller that behaves similarly to an alert — that is, it pops onto the screen and dims whatever is behind it — but it's your view controller and you are free to give it any interface you like.
To get you started, I've written a github project that you can download and run, and modify to suit your actual needs.
I'll show the key part of the code. The "alert" view controller, in its initializers, sets its own modal presentation style as custom and sets a transitioning delegate:
class CustomAlertViewController : UIViewController {
let transitioner = CAVTransitioner()
override init(nibName: String?, bundle: Bundle?) {
super.init(nibName: nibName, bundle: bundle)
self.modalPresentationStyle = .custom
self.transitioningDelegate = self.transitioner
}
convenience init() {
self.init(nibName:nil, bundle:nil)
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
}
All the work is done by the transitioning delegate:
class CAVTransitioner : NSObject, UIViewControllerTransitioningDelegate {
func presentationController(
forPresented presented: UIViewController,
presenting: UIViewController?,
source: UIViewController)
-> UIPresentationController? {
return MyPresentationController(
presentedViewController: presented, presenting: presenting)
}
}
class MyPresentationController : UIPresentationController {
func decorateView(_ v:UIView) {
// iOS 8 doesn't have this
// v.layer.borderColor = UIColor.blue.cgColor
// v.layer.borderWidth = 2
v.layer.cornerRadius = 8
let m1 = UIInterpolatingMotionEffect(
keyPath:"center.x", type:.tiltAlongHorizontalAxis)
m1.maximumRelativeValue = 10.0
m1.minimumRelativeValue = -10.0
let m2 = UIInterpolatingMotionEffect(
keyPath:"center.y", type:.tiltAlongVerticalAxis)
m2.maximumRelativeValue = 10.0
m2.minimumRelativeValue = -10.0
let g = UIMotionEffectGroup()
g.motionEffects = [m1,m2]
v.addMotionEffect(g)
}
override func presentationTransitionWillBegin() {
self.decorateView(self.presentedView!)
let vc = self.presentingViewController
let v = vc.view!
let con = self.containerView!
let shadow = UIView(frame:con.bounds)
shadow.backgroundColor = UIColor(white:0, alpha:0.4)
shadow.alpha = 0
con.insertSubview(shadow, at: 0)
shadow.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let tc = vc.transitionCoordinator!
tc.animate(alongsideTransition: { _ in
shadow.alpha = 1
}) { _ in
v.tintAdjustmentMode = .dimmed
}
}
override func dismissalTransitionWillBegin() {
let vc = self.presentingViewController
let v = vc.view!
let con = self.containerView!
let shadow = con.subviews[0]
let tc = vc.transitionCoordinator!
tc.animate(alongsideTransition: { _ in
shadow.alpha = 0
}) { _ in
v.tintAdjustmentMode = .automatic
}
}
override var frameOfPresentedViewInContainerView : CGRect {
// we want to center the presented view at its "native" size
// I can think of a lot of ways to do this,
// but here we just assume that it *is* its native size
let v = self.presentedView!
let con = self.containerView!
v.center = CGPoint(x: con.bounds.midX, y: con.bounds.midY)
return v.frame.integral
}
override func containerViewWillLayoutSubviews() {
// deal with future rotation
// again, I can think of more than one approach
let v = self.presentedView!
v.autoresizingMask = [
.flexibleTopMargin, .flexibleBottomMargin,
.flexibleLeftMargin, .flexibleRightMargin
]
v.translatesAutoresizingMaskIntoConstraints = true
}
}
extension CAVTransitioner { // UIViewControllerTransitioningDelegate
func animationController(
forPresented presented:UIViewController,
presenting: UIViewController,
source: UIViewController)
-> UIViewControllerAnimatedTransitioning? {
return self
}
func animationController(
forDismissed dismissed: UIViewController)
-> UIViewControllerAnimatedTransitioning? {
return self
}
}
extension CAVTransitioner : UIViewControllerAnimatedTransitioning {
func transitionDuration(
using transitionContext: UIViewControllerContextTransitioning?)
-> TimeInterval {
return 0.25
}
func animateTransition(
using transitionContext: UIViewControllerContextTransitioning) {
let con = transitionContext.containerView
let v1 = transitionContext.view(forKey: .from)
let v2 = transitionContext.view(forKey: .to)
// we are using the same object (self) as animation controller
// for both presentation and dismissal
// so we have to distinguish the two cases
if let v2 = v2 { // presenting
con.addSubview(v2)
let scale = CGAffineTransform(scaleX: 1.6, y: 1.6)
v2.transform = scale
v2.alpha = 0
UIView.animate(withDuration: 0.25, animations: {
v2.alpha = 1
v2.transform = .identity
}) { _ in
transitionContext.completeTransition(true)
}
} else if let v1 = v1 { // dismissing
UIView.animate(withDuration: 0.25, animations: {
v1.alpha = 0
}) { _ in
transitionContext.completeTransition(true)
}
}
}
}
It looks like a lot of code, and I suppose it is, but it's almost entire confined to a single class, which is entirely boilerplate; just copy and paste. All you have to do is write the internal interface and behavior of your "alert" view controller, giving it buttons and text and whatever else you want, just as you would do for any other view controller.
Custom Alert UIView Class in swift 4. And Usage ##
import UIKit
class Dialouge: UIView {
#IBOutlet weak var lblTitle: UILabel!
#IBOutlet weak var lblDescription: UILabel!
#IBOutlet weak var btnLeft: UIButton!
#IBOutlet weak var btnRight: UIButton!
#IBOutlet weak var viewBg: UIButton!
var leftAction = {}
var rightAction = {}
override func draw(_ rect: CGRect)
{
self.btnRight.layer.cornerRadius = self.btnRight.frame.height/2
self.btnLeft.layer.cornerRadius = self.btnLeft.frame.height/2
self.btnLeft.layer.borderWidth = 1.0
self.btnLeft.layer.borderColor = #colorLiteral(red: 0.267678082, green: 0.2990377247, blue: 0.7881471515, alpha: 1)
}
#IBAction func leftAction(_ sender: Any) {
leftAction()
}
#IBAction func rightAction(_ sender: Any) {
rightAction()
}
#IBAction func bgTapped(_ sender: Any) {
self.removeFromSuperview()
}
}
strong text
## Usage Of Custom Alert with Tabbar.
let custView = Bundle.main.loadNibNamed("Dialouge", owner: self, options:
nil)![0] as? Dialouge
custView?.lblDescription.text = "Are you sure you want to delete post?"
custView?.lblTitle.text = "Delete Post"
custView?.btnLeft.setTitle("Yes", for: .normal)
custView?.btnRight.setTitle("No", for: .normal)
custView?.leftAction = {
self.deletePost(postId: self.curr_post.id,completion: {
custView?.removeFromSuperview()
})
}
custView?.rightAction = {
custView?.removeFromSuperview()
}
if let tbc = self.parentt?.tabBarController {
custView?.frame = tbc.view.frame
DispatchQueue.main.async {
tbc.view.addSubview(custView!)
}
}else if let tbc = self.parView?.parenttprof {
custView?.frame = tbc.view.frame
DispatchQueue.main.async {
tbc.view.addSubview(custView!)
}
}
else
{
custView?.frame = self.parView?.view.frame ?? CGRect.zero
DispatchQueue.main.async {
self.parView?.view.addSubview(custView!)
}
}
Use https://github.com/shantaramk/Custom-Alert-View
It is effortless to implement this. Follow the steps below:
Drag down the AlertView folder in project directory
Show AlertView Popup
func showUpdateProfilePopup(_ message: String) {
let alertView = AlertView(title: AlertMessage.success, message: message, okButtonText: LocalizedStrings.okay, cancelButtonText: "") { (_, button) in
if button == .other {
self.navigationController?.popViewController(animated: true)
}
}
alertView.show(animated: true)
}

Resources