Button on pop Up View doesn't work - ios

I was trying to create a button on my custom pop up view. But created button doesn't recognise its action.
func createPopUp(){
view.userInteractionEnabled = false
scrollerView.userInteractionEnabled = false
var screenSize:CGRect = UIScreen.mainScreen().bounds
var screenHeight = screenSize.height
var screenWidth = screenSize.width
var popUpView : UIImageView
popUpView = UIImageView(frame:CGRectMake(0, 0, 530, 150));
popUpView.center = CGPointMake(screenWidth/2,screenHeight/2)
popUpView.backgroundColor = UIColor.whiteColor()
popUpView.tag = 81
self.view.addSubview(popUpView)
var vazgecButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
vazgecButton.frame = CGRectMake(0, 0, 265, 60)
vazgecButton.center = CGPointMake(250, 550)
vazgecButton.setTitle("VazgeƧ", forState: .Normal)
vazgecButton.tag = 79
vazgecButton.addTarget(self, action: "closePopUpView:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(vazgecButton)
}
First i disabled user interacton for view and my scrollerView. Then i created a image view for pop up view, to keep my button. Neither adding on to popUpView nor view work.
and my closePopUpView is:
func closePopUpView(sender: UIButton!){
println("pressed!!")
}
I searched for internet but i couldn't find a solution.

Related

Xcode 10 - Scroll View is not allowing scrolling when adding button programmatically

I'm getting data from a database and trying to display the data as buttons, I have got this working but when I run the app on the Xcode simulator the buttons are showing and I can see they are off the screen but I can't scroll.
I have tried adding a "view" inside the "scroll view" with a fixed height and then adding the buttons to that view and still nothing.
// Adding the scroll view and the view
#IBOutlet weak var scroll: UIScrollView!
#IBOutlet weak var content: UIView!
// Button Settings
var buttonX = 100
var buttonY = 0
let buttonWidth = 200
let buttonHeight = 50
let image = UIImage(named: "button") as UIImage?
override func viewDidLoad() {
super.viewDidLoad()
for element in contentsArray {
// Adding a button for each client name
let button = UIButton(type: .system)
button.setTitle(element, for: .normal)
button.tintColor = .white
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 22)
button.setBackgroundImage(image, for: .normal)
button.centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true
button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
button.frame = CGRect(x: buttonX, y: buttonY, width: buttonWidth, height: buttonHeight)
content.addSubview(button)
buttonY = buttonY + 70
}
}
I am not getting any errors in the console when running the app.
Once your finish adding buttons, set the scrollView.contentSize.height to your calculated buttonY
scrollView.contentSize.width = self.view.frame.size.width // non scrollable content width
for element in contentsArray {
...
buttonY = buttonY + 70
}
scrollView.contentSize.height = buttonY // scrollable content height

When creating a lazy button with a frame, this is created on the upper left corner why this happen?

I create this 'filterButton' and set it to be created on the exact position of the 'menubutton', the 'filterButton' goes directly to the upper left corner of the view.
lazy var filterButton: UIButton! = {
let button = UIButton(frame: CGRect(x: self.menuButton.frame.origin.x, y: self.button.frame.origin.y, width: 45, height: 45))
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .blue
button.clipsToBounds = true
return button
}()
and when I check and print the frame of the 'filterButton' it has the value of the 'menuButton', why this is happening?.
Add following constraints where you are adding filterButton to your view
filterButton.leftAnchor.constraint(equalTo: menuButton.leftAnchor).isActive = true
filterButton.topAnchor.constraint(equalTo: menuButton.topAnchor).isActive = true
filterButton.rightAnchor.constraint(equalTo: menuButton.rightAnchor).isActive = true
filterButton.bottomAnchor.constraint(equalTo: menuButton.bottomAnchor).isActive = true
Maybe, when you access to the instance of filterButton, frames of menuButton and button is not correct.
You can use layout constraints or update frame of filterButton in viewDidLayoutSubviews.
the problem is not of lazy button check you menuButton the problem is there for that you can check this :-
lazy var filterButton: UIButton! = {
let button = UIButton(frame: CGRect(x: 200, y: 200, width: 45, height: 45))
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .blue
button.clipsToBounds = true
return button
}()

how to dismiss a UIView when tapped outside its bounds?

I have a View Controller that has a main view, inside that i have created a small drop down(a pop up menu) towards the right that is also a UIView. I have added a button that shows and dismisses this pop up menu view when tapped.
All is working fine.
But now I want it to dismiss the view when the user taps outside those bounds.
The current code is as follows
var vw = UIView()
func popup(){
vw = UIView(frame: CGRectMake(self.view.frame.size.width - 210, 20, 260, 320))
vw.backgroundColor = UIColor.whiteColor()
vw.layer.cornerRadius = 5.0
vw.layer.shadowColor = UIColor.blackColor().CGColor
vw.layer.shadowOpacity = 0.8
vw.layer.shadowRadius = 3.0
vw.layer.shadowOffset = CGSizeMake(2.0, 2.0)
let name: UILabel = UILabel(frame: CGRectMake(5, 0, 90, 30))
name.text = testUserName
name.font = UIFont(name: "Abc Lt", size: 20.0)
let orgName: UILabel = UILabel(frame: CGRectMake(5, 35, 90, 30))
orgName.text = "Abc Lt"
name.font = UIFont(name: "V Lt", size: 25.0)
let profileImageView: UIImageView = UIImageView(frame: CGRectMake(137, 4, 35, 35))
profileImageView.image = UIImage(named: "profilepic.png")
let dropUpButton: UIButton = UIButton(frame: CGRectMake(profileImageView.frame.origin.x + 42, 18, 15, 10))
// dropUpButton.imageView.image = [UIImage imageNamed:#"dropdown.png"];
dropUpButton.setImage(UIImage(named: "dropup.png"), forState: .Normal)
dropUpButton.addTarget(self, action: #selector(LandingPageViewController.hideView), forControlEvents: .TouchUpInside)
vw.addSubview(name)
vw.addSubview(orgName)
vw.addSubview(profileImageView)
vw.addSubview(dropUpButton)
self.drawLine()
let tableView: UITableView = UITableView(frame: CGRectMake(0, 70, vw.frame.size.width, vw.frame.size.height-40), style: .Plain)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.scrollEnabled = false
vw.addSubview(tableView)
self.navigationController!.view!.addSubview(vw)
}
//the function that displays and dismiss the pop up menu
func hideView() {
vw.hidden = true
}
I have read some posts where one can use a tap gesture to find where it's tapped, and based on that using an if/else condition it can be solved but I am not sure.
Also you can check the image that I have uploaded for better understanding:
What you can really do is to take main superview full size same as your screen size. give clear background to it.Take a contentview same as you are doing now. Add a button similar size to super view and on click selector you can remove view from superview.
There are also alternative ways for doing this by identifying touch location. But It takes lots of effort.
Hope this helps you.
You can use tap gesture to do that
add this code on main view:
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTap(_:)))
tap.delegate = self
self.view.addGestureRecognizer(tap)
and then
func handleTap(sender: UITapGestureRecognizer? = nil)
{
hideView()
}

addTarget not working for UIButton created in Swift

So, I've created a UIButton using Swift, and I animate it and it's superview using the following code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//create a UIView to contain buttons. Set background color to nil, so it's transparent.
var controlsView = UIView(frame: CGRect(x:0, y:0, width:400, height:400));
controlsView.alpha = 1.0
controlsView.backgroundColor = nil
//create a button and add some attributes. Self explanatory
var loginButton: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
loginButton.frame = CGRectMake(20.0, 40.0, 200, 60)
loginButton.alpha = 0.0
loginButton.setTitle("Login", forState: .Normal)
loginButton.titleColorForState(.Normal)
loginButton.layer.cornerRadius = 20;
loginButton.layer.borderWidth = 1.0
loginButton.layer.borderColor = CGColorCreate(CGColorSpaceCreateDeviceRGB(), [0.827, 0.325, 0.0, 1.0])
loginButton.addTarget(self, action: "loginPressed:", forControlEvents: .TouchUpInside)
//add the button to the view created to hold it
controlsView.addSubview(loginButton)
//now test blurring the background view. Create a UIVisualEffectView to create the blur effect. New in iOS7/8
/*
var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView
visualEffectView.frame = self.introImage.bounds
self.introImage.addSubview(visualEffectView)
visualEffectView.alpha = 0.0
*/
//add the controls subview to the image view already here.
self.introImage.addSubview(controlsView)
//loginButton.addTarget(self, action: "loginButtonWasPressed:",forControlEvents:.TouchUpInside)
UIView.animateWithDuration(0.7,
animations: {
loginButton.alpha = 1.0
loginButton.frame = CGRect(x: 20.0, y: 100.0, width: 200, height: 60)
//visualEffectView.alpha = 0.5
},
completion:nil)
}
That's working fine. Then I created a function which should be called on touchUpInside of the button I created above:
#IBAction func loginPressed(sender:UIButton){
var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();
}
When I touch the button, the function DOES NOT fire. Can anyone help? I'm testing this on an actual device (iPhone 6 Plus/iOS 8.1.1
To add an action to a button, you need to use the following code
loginButton.addTarget(self,action:#selector(loginPressed),
forControlEvents:.TouchUpInside)
This code is working fine for me.
For more detail you can follow this [Attach parameter to button.addTarget action in Swift
Thanks.

exc_bad_access on uibutton click using Xcode 6 and Swift language

I am trying to add another sub view on click of button.
First view is created using storyboard and button action is working fine.
But when I add new viewcontroller's view as subview and click on button, application crashes with exc_bad_access on iPhone Simulator.
here is the code:
override func viewDidLoad() {
super.viewDidLoad()
let datePick : UIDatePicker = UIDatePicker(frame: CGRectMake(0, 0, 218, 216))
datePick.backgroundColor = UIColor.whiteColor()
datePick.layer.borderColor = UIColor.blackColor().CGColor
datePick.layer.borderWidth = 5
let actionView : UIView = UIView(frame: CGRectMake(0, 216, datePick.frame.width, 50))
actionView.backgroundColor = UIColor.blackColor()
self.view.addSubview(datePick)
var cancelButton : UIButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
cancelButton.frame = CGRectMake(datePick.frame.width-80, 5, 60, 40)
cancelButton.setTitle("Cancel", forState: UIControlState.Normal)
cancelButton.backgroundColor = UIColor.redColor()
cancelButton.addTarget(self, action: "cancelPressed:", forControlEvents: UIControlEvents.TouchUpInside)
actionView.addSubview(cancelButton)
var doneButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
doneButton.frame = CGRectMake(20, 5, 60, 40)
doneButton.backgroundColor = UIColor.greenColor()
doneButton.setTitle("Done", forState: .Normal)
doneButton.addTarget(self, action: "buttonAction:",forControlEvents:UIControlEvents.TouchUpInside)
self.view.addSubview(actionView)
actionView.addSubview(doneButton)
// datePicker.frame = CGRectMake(0, 0, 218, 216);
// Do any additional setup after loading the view, typically from a nib.
}
func buttonAction(sender:UIButton!)
{
println("Button tapped")
}
func cancelPressed(sender: UIButton!) {
println("Cancel Clicked!!!")
}
IBAction Method called from first viewcontroller's view is :
#IBAction func dateSelectClicked (sender:AnyObject){
var datePicker = DatePicker()
datePicker.view.frame = CGRectMake(0, self.view.frame.height, self.view.frame.width, self.view.frame.height)
let isfinished : Bool = true
self.view.addSubview(datePicker.view)
UIView.animateWithDuration(0.5, delay: 1.0 , options: UIViewAnimationOptions.CurveEaseInOut, animations: { datePicker.view.frame = CGRectMake(0, self.view.frame.height-266, self.view.frame.width, self.view.frame.height)}, completion: {(isfinished) in println("finished")})
}
Change this 2 lines from:
self.view.addSubview(actionView)
actionView.addSubview(doneButton)
to:
actionView.addSubview(doneButton)
self.view.addSubview(actionView)
Finally I found the problem :
As provided in question, DatePicker viewcontroller was adding as :
var datePicker = DatePicker()
on click of button.(func dateSelectClicked)
So this is the problem with creating instance of DatePicker.
We need to create it as property outside method as :
Class firstViewController :UIViewController {
var datePicker = DatePicker()
}
and use as property in method self.datepicker

Resources