I have created my own label and my own button. Now when the page loads the label hides as I want but when i click the button it does not show up as it supposed to do, in fact it does not do anything. How can I fix this problem which is making label show when i press the button?
#IBOutlet var thumbsUpButtonaPressed : UIButton!
#IBOutlet weak var label : UILabel!
override func viewDidLoad() {
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "00000"
self.view.addSubview(label)
label.hidden = true
let buttona = UIButton()
buttona.frame = CGRectMake(0.772 * view.bounds.width, 0.32 * view.bounds.height, 22, 22)
buttona.layer.cornerRadius = 0.04 * view.bounds.width
buttona.backgroundColor = UIColor.greenColor()
buttona.setImage(UIImage(named:"A.png"), forState: .Normal)
buttona.addTarget(self, action: "thumbsUpButtonaPressed", forControlEvents: .TouchUpInside)
view.addSubview(button)
func thumbsUpButtonaPressed(sender: UIButton!) {
label.hidden = false
}
}
I am using below code on swift 3
label.isHidden = true // hide
label.isHidden = false // show
you can use isHidden with other ui objects, see that answer also
Unless I am missing something in viewDidLoad you are creating a new label
var label = ...
you are not using the IBOutlet Property like
label = ...
Also are you sure your brackets are correct because it looks like your buttonPressed method is nested inside viewDidLoad.
Create an IBAction:
#IBAction func thumbsUpButtonaPressed(sender: UIButton) {
label.hidden = false
}
Then connect it with your button by cmd + drag on the button to the action:
Swift 5 Update
#IBAction func thumbsUpButtonaPressed(sender: UIButton) {
label.isHidden = false
}
You can also change:
label.alpha = 1.0 // show
label.alpha = 0.0 // hide
Try to correct your function with:
func thumbsUpButtonaPressed(sender: UIButton!) {
print("button was pressed")
label.hidden = false
label.setNeedDisplay()
}
Create normal IBAction for your button:
#IBAction func thumbsUpButtonaPressed(sender: UIButton!) {
label.hidden = false
}
Related
I am trying to create a DropDownMenu class, but when I try to call addTarget to one of the buttons, this error comes up.
unrecognized selector sent to instance 0x7fd167f06120' terminating with uncaught exception of type NSException
I would really appreciate any help and no answer is a bad one!
Here is my entire class
class DropDownMenu: UIView {
// Main button or Pre
var main: UIButton! = UIButton(frame: CGRect(x: 0, y: 0, width: 46, height: 30))
var view: UIView!
// Title
var buttonTitles: [String]! = [""]
var titleColor: UIColor! = UIColor.black
var font: UIFont! = UIFont.systemFont(ofSize: 18)
// Individual Button
var buttonsBorderWidth: CGFloat! = 0
var buttonsBorderColor: UIColor? = UIColor.white
var buttonsCornerRadius: CGFloat! = 0
var color: UIColor! = UIColor.clear
// Button Images
var buttonsImageEdgeInsets: UIEdgeInsets? = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
var images: [UIImage]? = nil
// Onclick stuff
var target: UIViewController!
private var currentSelected: String? = nil
private var optionsStack = UIStackView()
init(main: UIButton) {
self.main = main
super.init(frame: CGRect())
}
func createDropDownMenu() {
main.addTarget(target, action: #selector(DropDownMenu.openDropdown(_:)), for: .touchUpInside)
print("Button Target?: \(main.allTargets), self.target: \(String(describing: target))")
let mainFrame = main.frame
optionsStack.frame = CGRect(x: mainFrame.minX, y: mainFrame.maxY, width: mainFrame.width, height: CGFloat(buttonTitles.count) * mainFrame.height)
optionsStack.axis = .vertical
view.addSubview(optionsStack)
var y: CGFloat! = 0
for title in buttonTitles {
let button = UIButton(frame: CGRect(x: 0, y: y, width: mainFrame.width, height: mainFrame.height))
button.setTitle(title, for: .normal)
button.setTitleColor(titleColor, for: .normal)
button.backgroundColor = color
button.titleLabel?.font = font
button.addTarget(target, action: #selector(DropDownMenu.onclick), for: .touchUpInside)
y += mainFrame.height
optionsStack.addArrangedSubview(button)
}
for button in optionsStack.arrangedSubviews {
button.isHidden = true
button.alpha = 0
}
}
#objc private func openDropdown(_ sender: UIButton) {
print("sender: \(String(describing: sender))")
optionsStack.arrangedSubviews.forEach { (button) in
UIView.animate(withDuration: 0.7) {
button.isHidden = !button.isHidden
button.alpha = button.alpha == 0 ? 1 : 0
self.view.layoutIfNeeded()
}
}
}
#objc private func onclick(_ sender: UIButton) {
let title = sender.titleLabel!.text
print(title as Any)
main.setTitle(title, for: .normal)
optionsStack.arrangedSubviews.forEach { (button) in
UIView.animate(withDuration: 0.7) {
button.isHidden = true
button.alpha = 0
}
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Here is the code and creation of the object in ViewController
let grade = UIButton(frame: CGRect(x: 50, y: 300, width: 80, height: 30))
grade.layer.borderWidth = 1
grade.setTitle("Grade", for: .normal)
grade.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
grade.setTitleColor(UIColor.black, for: .normal)
let gradeDP = DropDownMenu(main: main)
gradeDP.buttonTitles = ["Title 1", "Title 2", "Title 3"]
gradeDP.color = UIColor.gray
gradeDP.target = self
gradeDP.titleColor = UIColor.white
gradeDP.view = view
view.addSubview(grade)
gradeDP.createDropDownMenu()
The first print statement in the createDropDownMenu() function prints...
Button Target?: [AnyHashable(<HomeworkHelp.DropDownMenu: 0x7ffb555200b0; frame = (0 0; 0 0); layer = <CALayer: 0x600002bdf5c0>>)], self.target: Optional(<HomeworkHelp.CreateAccountViewController: 0x7ffb5550a7b0>)
After editing it with the help of mightknow I came up with this class. It doesn't have any onclick actions for the mainButton in it.
class DropDownMenu: UIStackView {
var options: [String]! = [] // Labels for all of the options
var titleButton: UIButton! = UIButton() // The Main Title Button
init(options: [String]) {
self.options = options
let mainFrame = titleButton.frame
super.init(frame: CGRect(x: mainFrame.minX, y: mainFrame.maxY, width: mainFrame.width, height: mainFrame.height * CGFloat(options.count)))
var y: CGFloat = 0
for title in self.options {
let button = UIButton(frame: CGRect(x: 0, y: y, width: self.frame.width, height: mainFrame.height))
button.setTitle(title, for: .normal)
button.setTitleColor(titleButton.titleLabel?.textColor, for: .normal)
button.backgroundColor = titleButton.backgroundColor
button.addTarget(self, action: #selector(dropDownOptionClicked(_:)), for: .touchUpInside)
button.isHidden = true
button.alpha = 0
self.addArrangedSubview(button)
y += 1
}
}
#objc func openDropDown(_ sender: UIButton) {
print("Open DropDownMenu")
for button in self.arrangedSubviews {
UIView.animate(withDuration: 0.7) {
button.isHidden = !button.isHidden
button.alpha = button.alpha == 0 ? 1 : 0
self.layoutIfNeeded()
self.superview?.layoutIfNeeded()
}
}
}
#objc private func dropDownOptionClicked(_ sender: UIButton) {
print(sender.titleLabel?.text as Any)
}
init() {
super.init(frame: CGRect.zero)
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
And than my ViewController is ...
let dp = DropDownMenu(options: ["Label 1", "Label 2", "Label 3"])
let titleButton = UIButton(frame: CGRect(x: 100, y: 300, width: 180, height: 40))
titleButton.backgroundColor = UIColor.white
titleButton.setTitle("DropDownMenu", for: .normal)
titleButton.setTitleColor(UIColor.black, for: .normal)
titleButton.layer.borderWidth = 2
titleButton.addTarget(self, action: #selector(dp.openDropDown(_:)), for: .touchUpInside)
dp.titleButton = titleButton
The error ...
Button Target?: [AnyHashable(<HomeworkHelp.DropDownMenu: 0x7ffb555200b0; frame = (0 0; 0 0); layer = <CALayer: 0x600002bdf5c0>>)], self.target: Optional(<HomeworkHelp.CreateAccountViewController: 0x7ffb5550a7b0>)
still comes up and I am clueless as to why.
You're setting the target as a UIViewController when the method you're calling is actually a method of the DropDownMenu class. What you need to do is set the target to self instead of the target property:
main.addTarget(self, action: #selector(DropDownMenu.openDropdown(_:)), for: .touchUpInside)
EDIT: In response to your comment, here is the code I'm using to test it. There are some layout/color choices I made just to make it clear to me, but this works:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let main = UIButton(frame: CGRect(x: 0, y: 100, width: 80, height: 30))
main.layer.borderWidth = 1
main.setTitle("Grade", for: .normal)
main.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
main.setTitleColor(UIColor.black, for: .normal)
let gradeDP = DropDownMenu(main: main)
gradeDP.buttonTitles = ["Title 1", "Title 2", "Title 3"]
gradeDP.color = UIColor.gray
gradeDP.target = self
gradeDP.titleColor = UIColor.white
gradeDP.view = UIView()
self.view.addSubview(gradeDP)
let b = self.view.bounds
gradeDP.frame = CGRect(x: b.minX, y: b.minY, width: b.width, height: b.height/2)
gradeDP.backgroundColor = UIColor.purple
gradeDP.target = self
gradeDP.addSubview(gradeDP.main)
gradeDP.createDropDownMenu()
}}
As for your code, I'm going on the assumption that the code you added in the second part of your question is inside your ViewController's viewDidLoad() method, and that the main variable you're using to initialize your DropDownMenu is an instance variable of your ViewController, because I'm not seeing it anywhere else in scope. If that's the case, there are definitely some issues. They are:
You never actually add gradeDP to your view hierarchy. If that's what the line gradeDP.view = view is supposed to do, it's not. What that code actually does is set the view property of gradeDP to be a reference to the ViewController's view property. And, unless there is code in your DropDownMenu class that you haven't included, you're not actually using that reference for anything. So, you can get rid of that line entirely, and the view property in your DropDownMenu class. If what you're trying to do is set the ViewController's view to be gradeDP, that code would be self.view = gradeDP, but I don't actually recommend doing it that way. A UIViewController's view property is used in some special functionality and probably shouldn't be messed with much. You probably want to add gradeDP as a subview, like I did in my code above.
The grade button you created is not used by your DropDownMenu. I'm guessing you meant to initialize with that instead of the main variable (that is out of scope of your code), like this:
let gradeDP = DropDownMenu(main: grade)
In short, unless there is code elsewhere that you haven't shared, what your code above does is create a UIButton labeled "Grade" that is visible but doesn't actually do anything (and isn't part of your DropDownMenu), and a DropDownMenu that isn't actually visible, but would have a main button that calls openDropdown(_:) if it was. I'm guessing that's not how it's supposed to work. Hopefully the code I provided above helps get you where you want to be, though.
As for suggestions with rebuilding your class so it works properly, you may want to start with something like this:
class DropDownMenu : UIView {
var dropdownOptions : [String] = []
private var titleButton : UIButton = UIButton()
private var optionsStack : UIStackView = UIStackView()
private var optionsButtons : [UIButton] = []
#objc private func openDropdown(_ sender: UIButton) {
// Add code to make dropdown options appear. There are multiple ways of doing this. For instance, the optionsButtons could be hidden and then unhidden when it's clicked, or they could be created only once the button is clicked.
}
#objc private func selectedOption(_ sender: UIButton) {
// Code here for when option is selected
}
init(options: [String]) {
self.dropdownOptions = options
super.init(frame: CGRect.zero)
// Customize all of your subviews here, and add them to your DropDownMenu (as subviews)
// Add openDropdown(_:) target to self.titleButton
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
A lot of the code you have already written for your original version of the class can go inside the functions there. Also, there is a lot of unnecessary code in your original version. For example, the target variable is unused once you fixed the original error issue, the view variable is obsolete, and the createDropDownMenu() function is unnecessary because all of that code can go either in the init(options:) or openDropdown(_:) functions.
Then, if you choose to build out a class using that template, you would implement it in your ViewController's viewDidLoad() method with the code:
let dropdown = DropDownMenu(titles: ["Title 1", "Title 2", "Title 3"])
self.view.addSubview(dropdown)
// Follow that with layout code that ensures it's the proper size and in the proper location
I hope that combined with my comments make sense, are helpful, and aren't too overwhelming. What I recommend doing is starting a new empty project (or target) and building your class and adding it to a ViewController with nothing else in it. That's a good way to isolate it and check and make sure everything looks and works right. In case you want an alternate suggestion with how to build your class, you can actually try making DropDownMenu be a subclass of UIStackView (instead of UIView) with the main button and all option buttons being arranged subviews. This might actually be simpler, because it kind of cuts out the middleman, if you will, and all you'd need to do when opening/closing the dropdown is add/remove views from the .arrangedSubviews property.
Also important is that if your view needs to pass information (such as which option is selected) back to the ViewController, make sure the reference to the ViewController is marked weak so you don't create a retain cycle.
On a final note, if you're disappointed that there isn't a quick fix to get the original class to work and want to keep trying at that, there might be some way to cobble together a solution (like the code from my first answer, which does actually work...), but ultimately it will probably only cause more issues further down the line. So, best of luck with everything.
I finally figured it out! The target has to be the DropDownMenu.
titleButton.addTarget(dp, action: #selector(dp.openDropDown(_:)), for: .touchUpInside)
Here is the rest of the code...
let titleButton = UIButton(frame: CGRect(x: 50, y: 290, width: 100, height: 40))
titleButton.backgroundColor = UIColor.white
titleButton.setTitle("Grade", for: .normal)
titleButton.setTitleColor(UIColor.black, for: .normal)
titleButton.layer.borderWidth = 2
titleButton.layer.cornerRadius = 10
let dp = DropDownMenu(options: ["1", "Freshman", "Sophomore", "Junior", "Senior", "College"])
dp.titleButton = titleButton
dp.target = self
dp.borderWidth = 2
dp.spacing = 5
dp.cornerRadius = 10
dp.bgColor = UIColor.white
Adding it to subviews and creating it...
view.addSubview(titleButton)
view.addSubview(dp)
dp.createDropDownMenu()
I create UITextView with a random tag and text, but it is created with one variable, is it possible to update the variable after creation UITextView (by clicking the add button)? Maybe add a random number to it, for example newText1, newText2.. etc.
So that the next UITextView is already created with a new variable?
P.S Sorry, if the question is silly, I just recently started to study Swift
#IBOutlet weak var addTextButton: UIButton!
#IBOutlet weak var StoriesView: UIView!
var newText = UITextView()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func addTextButton(_ sender: Any) {
let maxNumber = 10000
let i = Int(arc4random_uniform(UInt32(maxNumber)))
newText = UITextView(frame: CGRect(x: self.StoriesView.frame.origin.x + 40, y: self.StoriesView.frame.origin.y + 40, width: 380, height: 80))
self.StoriesView.addSubview(newText)
newText.font = UIFont(name: "Verdana", size: 11)
newText.text = "TAP TO EDIT #\(i)"
newText.sizeToFit()
newText.textColor = UIColor.black
newText.backgroundColor = UIColor.clear
newText.tag = i
newText.isEditable = true
newText.isSelectable = true
newText.isUserInteractionEnabled = true
newText.allowsEditingTextAttributes = true
newText.translatesAutoresizingMaskIntoConstraints = true
newText.enablesReturnKeyAutomatically = true
newText.delegate = self
}
UPD:
let fontToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
fontToolbar.barStyle = .default
fontToolbar.items = [
UIBarButtonItem(title: "Green", style: .plain, target: self, action: #selector(greenColor)),
UIBarButtonItem(title: "Blue", style: .plain, target: self, action: #selector(blueColor)),
UIBarButtonItem(title: "Red", style: .plain, target: self, action: #selector(redColor)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Close Keyboard", style: .plain, target: self, action: #selector(dismissKeyboard))]
fontToolbar.sizeToFit()
newText.inputAccessoryView = fontToolbar
in the toolBar above the keyboard I have buttons, here we change the color
#objc func redColor() {
newText.textColor = UIColor.red}
#objc func blueColor() {
newText.textColor = UIColor.blue}
#objc func greenColor() {
newText.textColor = UIColor.green}
So the color changes only in the newly created UITextView
On click of button, create a new texView and assign it a tag value. Once it is added, update the value of i to +1, so that every textView added has a new tag value.
var i = 1
var newText = UITextView()
#IBAction func addTextButton(_ sender: Any) {
newText = UITextView(frame: CGRect(x: self.StoriesView.frame.origin.x + 40, y: self.StoriesView.frame.origin.y + 40, width: 380, height: 80))
self.StoriesView.addSubview(newText)
newText.font = UIFont(name: "Verdana", size: 11)
newText.text = "TAP TO EDIT #\(i)"
newText.sizeToFit()
newText.textColor = UIColor.black
newText.backgroundColor = UIColor.clear
newText.tag = i
newText.isEditable = true
newText.isSelectable = true
newText.isUserInteractionEnabled = true
newText.allowsEditingTextAttributes = true
newText.translatesAutoresizingMaskIntoConstraints = true
newText.enablesReturnKeyAutomatically = true
newText.delegate = self
//increment i
i+=1
}
then you can access your textField via tag values like this:
if let textView = self.StoriesView.viewWithTag(i) as? UITextView {
// textView.text = "change it"
}
UPDATE:
Add textView Delegate method, and once a textView starts editing, change the newText value to the currently editing textView
class ViewController : UIViewController, UITextViewDelegate {
func textViewDidBeginEditing(_ textView: UITextView) {
newText = textView
}
}
I have modified your code a bit to have new UITextView object with button click
import UIKit
class ScannerViewController: UIViewController, UITextViewDelegate {
#IBOutlet weak var StoriesView: UIView!
#IBOutlet weak var addTextButton: UIButton!
var yposition: CGFloat!
var textFieldTag: [Int]! = []
override func viewDidLoad() {
super.viewDidLoad()
yposition = 20
}
#IBAction func addTextButton(_ sender: Any) {
let xposition = self.StoriesView.frame.origin.x
let maxNumber = 10000
let i = Int(arc4random_uniform(UInt32(maxNumber)))
textFieldTag.append(i)
let newText = UITextView(frame: CGRect(x: xposition , y: yposition , width: 380, height: 40))
self.StoriesView.addSubview(newText)
newText.font = UIFont(name: "Verdana", size: 11)
newText.text = "TAP TO EDIT #\(i)"
newText.sizeToFit()
newText.textColor = UIColor.black
newText.backgroundColor = UIColor.yellow
newText.tag = i
newText.isEditable = true
newText.isSelectable = true
newText.isUserInteractionEnabled = true
newText.allowsEditingTextAttributes = true
newText.translatesAutoresizingMaskIntoConstraints = true
newText.enablesReturnKeyAutomatically = true
newText.delegate = self
yposition = yposition + 45
}
#IBAction func accessTextFields(_ sender: Any) {
//access all text fields
for tag in textFieldTag {
if let textField = self.StoriesView.viewWithTag(tag) as? UITextView {
//change properties here
textField.backgroundColor = .cyan
}
}
//access specific text fields
if let textField = self.StoriesView.viewWithTag(textFieldTag.first!) as? UITextView {
//change properties here
textField.backgroundColor = .orange
}
if let textField = self.StoriesView.viewWithTag(textFieldTag[textFieldTag.count - 1]) as? UITextView {
//change properties here
textField.backgroundColor = .green
}
}
}
It will have an output as this!!
I'm using a UITextView to display some contents. Beneath the textView, I added a UIButton that can control if the TextView will display part or all of its content.
Ideally, when button tapped, the TextView will expand its Height to accommodate the length of the content.
I haven't found a good solution. I wonder if I should use UIlabel instead of textView.
You can make this thing working this way:
1. Add a UITextView and UIButton in Storyboard.
2. If you are using Autolayout Constraints, make an outlet of UITextView height.
3. In ViewController class make outlets as:
#IBOutlet var txtView: UITextView!
#IBOutlet var btn_Show: UIButton!
#IBOutlet var textView_HeightConstraint: NSLayoutConstraint!
4. Make a method that will give you height of UITextView according to the text in it.
func getRowHeightFromText(strText : String!) -> CGFloat
{
let textView : UITextView! = UITextView(frame: CGRect(x: self.txtView.frame.origin.x,
y: 0,
width: self.txtView.frame.size.width,
height: 0))
textView.text = strText
textView.font = UIFont(name: "Fira Sans", size: 16.0)
textView.sizeToFit()
var txt_frame : CGRect! = CGRect()
txt_frame = textView.frame
var size : CGSize! = CGSize()
size = txt_frame.size
size.height = 50 + txt_frame.size.height
return size.height
}
5. On Click of Button:
#IBAction func showMore_Button_Clicked(_ sender: UIButton)
{
if sender.tag == 0
{
let height = self.getRowHeightFromText(strText: self.txtView.text)
self.textView_HeightConstraint.constant = height
self.view.layoutIfNeeded()
btn_Show.setTitle("ShowLess", for: .normal)
sender.tag = 1
}
else
{
self.textView_HeightConstraint.constant = 116
self.view.layoutIfNeeded()
btn_Show.setTitle("ShowMore", for: .normal)
sender.tag = 0
}
}
6. If you are not using AutoLayoutConstraints, just change the Frame(Height) of UITextView on click of UIButton. No need of "textView_HeightConstraint"
#IBAction func showMore_Button_Clicked(_ sender: UIButton)
{
if sender.tag == 0
{
let height = self.getRowHeightFromText(strText: self.txtView.text)
self.txtView.frame = CGRect(x: self.txtView.frame.origin.x, y: self.txtView.frame.origin.y, width: self.txtView.frame.size.width, height: height)
btn_Show.setTitle("ShowLess", for: .normal)
sender.tag = 1
}
else
{
self.txtView.frame = CGRect(x: self.txtView.frame.origin.x, y: self.txtView.frame.origin.y, width: self.txtView.frame.size.width, height: 116)
btn_Show.setTitle("ShowMore", for: .normal)
sender.tag = 0
}
}
I'm currently using Xcode 7.3 and I'm simply wondering how to select multiple buttons across different UIViews, but under a single view controller. CMD clicking doesn't seem to work. I need this functionality because in Xcode 7.3 the only way to let two buttons on IB to share the same action is to select them at once and then drag the action to your view controller. I'm doing this by code and no drag & drop
class LogIn: UIViewController {
var mail_tf : UITextField!
var pass_tf : UITextField!
var btnL : UIButton!
var btnC : UIButton!
let cl1 = UIColor (red: 255/255.0, green: 258/255.0, blue: 196/255.0, alpha: 1)
let cl2 = UIColor (red: 238/255.0, green: 233/255.0, blue: 191/255.0, alpha: 1)
override func loadView() {
super.loadView()
let backgroundView = UIImageView(image: UIImage(named: "4")!)
//backgroundView.layer.cornerRadius = backgroundView.frame.size.width / 2
backgroundView.frame = CGRectMake(0, 0, 900, 900)
//backgroundView.clipsToBounds = true
//backgroundView.layer.borderColor = UIColor.whiteColor().CGColor
// backgroundView.layer.borderWidth = 1
self.view.addSubview(backgroundView)
mail_tf = UITextField()
mail_tf.frame = CGRectMake(95, 90, 190, 60)
mail_tf.layer.cornerRadius = 10
mail_tf.layer.borderWidth = 1
mail_tf.layer.borderColor = UIColor.blackColor().CGColor
mail_tf.placeholder = "e-mail"
mail_tf.textColor = UIColor.redColor()
mail_tf.backgroundColor = cl1
mail_tf.borderStyle = UITextBorderStyle.RoundedRect
self.view.addSubview(mail_tf)
pass_tf = UITextField()
pass_tf.frame = CGRectMake(95, 190, 190, 60)
pass_tf.layer.cornerRadius = 10
pass_tf.layer.borderWidth = 1
pass_tf.layer.borderColor = UIColor.blackColor().CGColor
pass_tf.placeholder = "password"
pass_tf.secureTextEntry = true
pass_tf.textColor = UIColor.redColor()
pass_tf.backgroundColor = cl1
pass_tf.borderStyle = UITextBorderStyle.RoundedRect
self.view.addSubview(pass_tf)
btnL = UIButton()
btnL.frame = CGRectMake(195, 260, 90, 40)
btnL.setTitle("Log In ", forState: UIControlState.Normal)
btnL.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
btnL.layer.borderWidth = 1
btnL.layer.borderColor = UIColor.blackColor().CGColor
btnL.layer.cornerRadius = 10
btnL.backgroundColor = cl1
self.view.addSubview(btnL)
btnL.addTarget(self , action: #selector(self.action(_:)), forControlEvents: UIControlEvents.TouchUpInside)
btnC = UIButton()
btnC.frame = CGRectMake(228, 350, 150, 40)
btnC.setTitle("Create new account ", forState: UIControlState.Normal)
btnC.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
btnC.layer.borderWidth = 1
btnC.layer.borderColor = UIColor.blackColor().CGColor
btnC.layer.cornerRadius = 10
btnC.backgroundColor = cl1
self.view.addSubview(btnC)
btnC.addTarget(self , action: #selector(self.action(_:)), forControlEvents: UIControlEvents.TouchUpInside)
}
func action (sender: UIButton!) {
// btnL & btnC open the Logged_in file . there is the problem
let vc = Logged_In()
let navigation = UINavigationController(rootViewController:vc)
self.navigationController?.presentViewController(navigation, animated: true, completion: nil)
let vc1 = create()
let navigation1 = UINavigationController(rootViewController:vc1)
self.navigationController?.presentViewController(navigation1, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Log in"
self.navigationController?.navigationBar.barTintColor = UIColor.blackColor()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: cl1]
}
}
EDITED ANSWER:
Okay, I think I understand what you are asking now. You want to have the same function action(sender: UIButton) do a different action depending on the button that calls it.
You can actually set a variable called tag and set a number to make it unique. For example btnL.tag = 0 and btnC.tag = 1
So then your function action would look like this:
func action (sender: UIButton!) {
if sender.tag == 0 {
let vc = Logged_In()
let navigation = UINavigationController(rootViewController:vc)
self.navigationController?.presentViewController(navigation, animated: true, completion: nil)
} else if sender.tag == 1 {
let vc1 = create()
let navigation1 = UINavigationController(rootViewController:vc1)
self.navigationController?.presentViewController(navigation1, animated: true, completion: nil)
}
}
A UIButton has a function that does this, specifically:
public func addTarget(target: AnyObject?, action: Selector, forControlEvents controlEvents: UIControlEvents)
The buttons need to be declared like this: #IBOutlet var button: UIButton above the class.
To add an action we call the above function in your class (viewController) that has access to variable button:
button.addTarget(self, action: #selector(self.sender(_:)), forControlEvents: .TouchDown)
You'll need to repeat this for each UIButton but the selector function will just be the same (ei, button1.addTarget(...), button2.addTarget(...), etc).
Your function will look something like this:
func sender(sender: UIButton) { }
You can probably iterate through all the buttons you want to add action to
for button in [button1, button2, button3, button4] {
button.addTarget(self, action: #selector(self.someFunction), forControlEvents: .TouchUpInside)
}
Search for all of your buttons and add the same target:
override func viewDidLayoutSubviews() {//This cannot be view did load; it can be view did appear or view will appear
super.viewDidLayoutSubviews()
for subview in self.view.subviews {
if let button = subview as? UIButton {
button.addTarget(target: self, action: #selector(self.someFunc), forControlEvents: .touchUpInside)
}
}
}
How to Add floating button as Facebook's App Rooms using the storyboard?
I can't drag UIView on the tableview that's the only way I know.
This button code below:
Adds Shadow
Makes the button round
Adds an animation to draw attention
Swift 4.2: COMPLETE VIEW CONTROLLER IMPLEMENTATION
import Foundation
public class FloatingButtonViewController: UIViewController {
private var floatingButton: UIButton?
// TODO: Replace image name with your own image:
private let floatingButtonImageName = "NAME OF YOUR IMAGE"
private static let buttonHeight: CGFloat = 75.0
private static let buttonWidth: CGFloat = 75.0
private let roundValue = FloatingButtonViewController.buttonHeight/2
private let trailingValue: CGFloat = 15.0
private let leadingValue: CGFloat = 15.0
private let shadowRadius: CGFloat = 2.0
private let shadowOpacity: Float = 0.5
private let shadowOffset = CGSize(width: 0.0, height: 5.0)
private let scaleKeyPath = "scale"
private let animationKeyPath = "transform.scale"
private let animationDuration: CFTimeInterval = 0.4
private let animateFromValue: CGFloat = 1.00
private let animateToValue: CGFloat = 1.05
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
createFloatingButton()
}
public override func viewWillDisappear(_ animated: Bool) {
guard floatingButton?.superview != nil else { return }
DispatchQueue.main.async {
self.floatingButton?.removeFromSuperview()
self.floatingButton = nil
}
super.viewWillDisappear(animated)
}
private func createFloatingButton() {
floatingButton = UIButton(type: .custom)
floatingButton?.translatesAutoresizingMaskIntoConstraints = false
floatingButton?.backgroundColor = .white
floatingButton?.setImage(UIImage(named: floatingButtonImageName), for: .normal)
floatingButton?.addTarget(self, action: #selector(doThisWhenButtonIsTapped(_:)), for: .touchUpInside)
constrainFloatingButtonToWindow()
makeFloatingButtonRound()
addShadowToFloatingButton()
addScaleAnimationToFloatingButton()
}
// TODO: Add some logic for when the button is tapped.
#IBAction private func doThisWhenButtonIsTapped(_ sender: Any) {
print("Button Tapped")
}
private func constrainFloatingButtonToWindow() {
DispatchQueue.main.async {
guard let keyWindow = UIApplication.shared.keyWindow,
let floatingButton = self.floatingButton else { return }
keyWindow.addSubview(floatingButton)
keyWindow.trailingAnchor.constraint(equalTo: floatingButton.trailingAnchor,
constant: self.trailingValue).isActive = true
keyWindow.bottomAnchor.constraint(equalTo: floatingButton.bottomAnchor,
constant: self.leadingValue).isActive = true
floatingButton.widthAnchor.constraint(equalToConstant:
FloatingButtonViewController.buttonWidth).isActive = true
floatingButton.heightAnchor.constraint(equalToConstant:
FloatingButtonViewController.buttonHeight).isActive = true
}
}
private func makeFloatingButtonRound() {
floatingButton?.layer.cornerRadius = roundValue
}
private func addShadowToFloatingButton() {
floatingButton?.layer.shadowColor = UIColor.black.cgColor
floatingButton?.layer.shadowOffset = shadowOffset
floatingButton?.layer.masksToBounds = false
floatingButton?.layer.shadowRadius = shadowRadius
floatingButton?.layer.shadowOpacity = shadowOpacity
}
private func addScaleAnimationToFloatingButton() {
// Add a pulsing animation to draw attention to button:
DispatchQueue.main.async {
let scaleAnimation: CABasicAnimation = CABasicAnimation(keyPath: self.animationKeyPath)
scaleAnimation.duration = self.animationDuration
scaleAnimation.repeatCount = .greatestFiniteMagnitude
scaleAnimation.autoreverses = true
scaleAnimation.fromValue = self.animateFromValue
scaleAnimation.toValue = self.animateToValue
self.floatingButton?.layer.add(scaleAnimation, forKey: self.scaleKeyPath)
}
}
}
Its a bit late, but may be it can help someone. You can do it very easily via programatically. Just create an instance of the button, set the desired property of button It is preferable to use constraints over frame cause it'll render the button at same position on every screen size. I am posting the code which will make the button round. Play with the value of constraints to change the position and size of button.
Swift 3
var roundButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
self.roundButton = UIButton(type: .custom)
self.roundButton.setTitleColor(UIColor.orange, for: .normal)
self.roundButton.addTarget(self, action: #selector(ButtonClick(_:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(roundButton)
}
override func viewWillLayoutSubviews() {
roundButton.layer.cornerRadius = roundButton.layer.frame.size.width/2
roundButton.backgroundColor = UIColor.lightGray
roundButton.clipsToBounds = true
roundButton.setImage(UIImage(named:"your-image"), for: .normal)
roundButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
roundButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -3),
roundButton.bottomAnchor.constraint
(equalTo: self.view.bottomAnchor, constant: -53),
roundButton.widthAnchor.constraint(equalToConstant: 50),
roundButton.heightAnchor.constraint(equalToConstant: 50)])
}
/** Action Handler for button **/
#IBAction func ButtonClick(_ sender: UIButton){
/** Do whatever you wanna do on button click**/
}
Put a table view inside a view controller. You should then be able to add the the button on top of the table view.
Following the answer of #Kunal Kumar, it works on the UIScrollView, and UIView, but it doesn't works on the UITableView. I found it is easy to make it works with UITableView, only need to add one line code. Thank you so much #Kunal Kumar
in the viewDidLoad, change self.view.addSubview(roundButton) to
self.navigationController?.view.addSubview(roundButton) and it will work!!
by the way, I think we need to add super.viewWillLayoutSubviews() in the viewWillLayoutSubviews() method.
below is the all code with above mentioned,
Swift 3
// MARK: Floating Button
var roundButton = UIButton()
func createFloatingButton() {
self.roundButton = UIButton(type: .custom)
self.roundButton.setTitleColor(UIColor.orange, for: .normal)
self.roundButton.addTarget(self, action: #selector(ButtonClick(_:)), for: UIControlEvents.touchUpInside)
//change view to navigationController?.view, if you have a navigationController in this tableview
self.navigationController?.view.addSubview(roundButton)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
roundButton.layer.cornerRadius = roundButton.layer.frame.size.width/2
roundButton.backgroundColor = UIColor.lightGray
roundButton.clipsToBounds = true
roundButton.setImage(UIImage(named:"ic_wb_sunny_48pt"), for: .normal)
roundButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
roundButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -3),
roundButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -53),
roundButton.widthAnchor.constraint(equalToConstant: 50),
roundButton.heightAnchor.constraint(equalToConstant: 50)])
}
It's simply because your UIButton is under the UITableView, move it in the storyboard's tree so it appears like this :
| View
|-- Table View
|-- Button