Swift4 addTarget at UIButton doesnt work in UIView - swift

I programmatically created an UIButton and added it to a subview. AddTarget doesnt work there though. AddTarget only works if I add the button to the mainview.
self.view.addSubview(button)
instead of
ViewSystem.addSubview(button)
Doesnt anyone know why?
Here is the fullcode:
class ViewController: UIViewController {
var ViewSystem = UIView()
#objc func TestPressed(sender: UIButton?) {Test.text=String((sender?.tag)!)
func ButtonCreate () {
let button = UIButton()
button.frame = CGRect(x: 50, y: 100, width: 70, height: 70)
button.addTarget(self, action: #selector(TestPressed), for: .touchUpInside)
button.backgroundColor = UIColor.red
button.tag=5
ViewSystem.addSubview(button)
self.view.addSubview(ViewSystem)
}
}

This happening because you are set your button frame graterthen your view that's why your button not tapped.
you are not set your view frame and then how you can you set your button inside your view.
Here I update your ButtonCreate () function code it's working nicely.
func ButtonCreate () {
ViewSystem.frame = CGRect(x: 50, y: 100, width: 200, height: 70)
ViewSystem.backgroundColor = .blue
let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
button.addTarget(self, action: #selector(TestPressed), for: .touchUpInside)
button.backgroundColor = UIColor.red
button.tag = 5
ViewSystem.clipsToBounds = false
ViewSystem.addSubview(button)
self.view.addSubview(ViewSystem)
}
I hope it's helpfull for you and save your time

You have to give frame to your ViewSystem. and ViewSystem's height width should be greater than button's X and Y.
var ViewSystem = UIView()
ViewSystem.frame = CGRect(x: 50, y: 100, width: 70, height: 70)
#objc func TestPressed(sender: UIButton?) {Test.text=String((sender?.tag)!)
func ButtonCreate () {
let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
button.addTarget(self, action: #selector(TestPressed), for: .touchUpInside)
button.backgroundColor = UIColor.red
button.tag=5
ViewSystem.addSubview(button)
self.view.addSubview(ViewSystem)
}
}

Related

swift can't find textfield in scope even when its in the same viewController

I need to print value of txtField after clicking the button, txtField is on the viewcotroller but xcode returns an error cannot find 'txtField' in scope but they are in the same view
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.backgroundColor = .green
button.setTitle("Test Button", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
var txtField: UITextField = UITextField()
txtField.frame = CGRect(x: 50, y: 70, width: 200, height: 30)
txtField.backgroundColor = UIColor.gray
self.view.addSubview(txtField)
}
#objc func buttonAction(sender: UIButton!) {
print(txtField.text)
}
Actually, no, it's not in scope. Your var txtField is inside the viewDidLoad function. No other function's code can see inside this function, so the variable is not in scope from within another function such as your buttonAction.
In general the rule that things inside a scope can see only things that at a higher level of scope. If var txtField appeared outside both viewDidLoad and buttonAction (i.e. an instance property), then code inside both would be able to see it.
It's an easy move to make:
var txtField: UITextField = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.backgroundColor = .green
button.setTitle("Test Button", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
txtField.frame = CGRect(x: 50, y: 70, width: 200, height: 30)
txtField.backgroundColor = UIColor.gray
self.view.addSubview(txtField)
}
#objc func buttonAction(sender: UIButton!) {
print(txtField.text)
}
The error is that are in 2 different function, override or #objc doesn't change this simple thing. So move the txtField initialization outside them so can be readed or written by both.
var txtField: UITextField = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.backgroundColor = .green
button.setTitle("Test Button", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
txtField.frame = CGRect(x: 50, y: 70, width: 200, height: 30)
txtField.backgroundColor = UIColor.gray
self.view.addSubview(txtField)
}
#objc func buttonAction(sender: UIButton!) {
print(txtField.text)
}
In your code txtField is declared in viewDidLoad on line
var txtField: UITextField = UITextField()
Therefore out of the scope of buttonAction.
To mitigate this place
txtField
out of scope as a instance variable

Swift 5: My barbutton in navigationbar wasn't fit

Here is my image:
And I put it in rightbarbuttonitem, and it is not fit with area.
This is result
Here is my code:
let button = UIButton(type: .custom)
button.setImage(UIImage (named: "Group 4"), for: .normal)
button.frame = CGRect(x: 0.0, y: 0.0, width: 35, height: 35)
//button.addTarget(target, action: nil, for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButtonItem
Please help me!!!
Can you try this instead of your code?
let rightBarButtonItem = UIButton(frame: CGRect(x: 0, y: 0, width: 36, height: 36))
rightBarButtonItem.setBackgroundImage(UIImage(named: "Group 4"), for: .normal)
rightBarButtonItem.addTarget(self, action: #selector(actionRightBar), for: .touchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBarButtonItem)

One UI element for all VC [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How I can create Custom view element with animation like a separate class for all view controllers, so that not write this element each time for each VC.
For example:
I am want create bottom view with button and if I am press on button animation will be appeared, and I am can do different action for different VC.
How I can create this view with animation one time for all VC and implement different action inside VC?
I can only create it each time for each VC, all work done but it's terrible code and sometimes may be hard for maintenance.
This it example how I am create my bottom menu and this way looking good but how work.
import Foundation
import UIKit
class BottomMenu: UIViewController {
static let shared = BottomMenu()
var yPosBottomUIView: CGFloat = 90.0
var yPosCenterButton: CGFloat = 35
var yPosBackButton: CGFloat = 35
var yPosForwardButton: CGFloat = 35
var yPosContextMenu: CGFloat = 35
var yPosUpdateButton: CGFloat = 35
var backButtonEnable: Bool = false
var forwardButtonEnable: Bool = false
lazy var image: UIImageView = {
let image = UIImageView(frame: CGRect(x: 0, y: UIScreen.main.bounds.maxY - yPosBottomUIView, width: UIScreen.main.bounds.width, height: 90))
if (osTheme == .dark) {
DispatchQueue.main.async {
image.image = UIImage(named: "SurfaceBlack")
}
return image
} else {
DispatchQueue.main.async {
image.image = UIImage(named: "SurfaceLight")
}
return image
}
}()
lazy var centerButton: UIButton = {
let button = UIButton(frame: CGRect(x: (UIScreen.main.bounds.maxX / 2) - 25, y: (UIScreen.main.bounds.maxY - 50) - yPosCenterButton, width: 50, height: 50))
if (osTheme == .dark) {
button.backgroundColor = UIColor(red: 0.118, green: 0.118, blue: 0.15, alpha: 1)
} else {
button.backgroundColor = UIColor(red: 0.118, green: 0.118, blue: 0.15, alpha: 1)
}
button.layer.cornerRadius = 25
button.setImage(UIImage(named: "Menu"), for: .normal)
button.addTarget(self, action: #selector(centralButtonAction), for: .touchUpInside)
button.isEnabled = false
return button
}()
lazy var backButton: UIButton = {
let button = UIButton(frame: CGRect(x: (UIScreen.main.bounds.minX) + 25, y: (UIScreen.main.bounds.maxY - 15.5) - yPosBackButton, width: 36, height: 36))
button.backgroundColor = .clear
button.setImage(UIImage(named: "whiteBackArrow"), for: .normal)
button.addTarget(self, action: #selector(centralButtonAction), for: .touchUpInside)
button.isEnabled = backButtonEnable
return button
}()
lazy var forwardButton: UIButton = {
let button = UIButton(frame: CGRect(x: (UIScreen.main.bounds.minX) + 90, y: (UIScreen.main.bounds.maxY - 15.5) - yPosForwardButton, width: 36, height: 36))
button.backgroundColor = .clear
button.setImage(UIImage(named: "whiteBackArrow"), for: .normal)
button.imageView?.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
button.addTarget(self, action: #selector(centralButtonAction), for: .touchUpInside)
button.isEnabled = forwardButtonEnable
return button
}()
lazy var contextMenu: UIButton = {
let button = UIButton(frame: CGRect(x: (UIScreen.main.bounds.maxX) - 60, y: (UIScreen.main.bounds.maxY - 15.5) - yPosContextMenu, width: 36, height: 36))
button.backgroundColor = .clear
button.setImage(UIImage(named: "ContextMenu"), for: .normal)
button.addTarget(self, action: #selector(contextMenuButtonAction), for: .touchUpInside)
return button
}()
lazy var updateButton: UIButton = {
let button = UIButton(frame: CGRect(x: (UIScreen.main.bounds.maxX) - 125, y: (UIScreen.main.bounds.maxY - 15.5) - yPosUpdateButton, width: 36, height: 36))
button.backgroundColor = .clear
button.setImage(UIImage(named: "updateN"), for: .normal)
button.addTarget(self, action: #selector(centralButtonAction), for: .touchUpInside)
button.isEnabled = false
return button
}()
lazy var blur: UIVisualEffectView = {
let blurEffectView = UIVisualEffectView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
let blurEffect = UIBlurEffect(style: .dark)
blurEffectView.effect = blurEffect
blurEffectView.alpha = 0
return blurEffectView
}()
#objc func centralButtonAction(_ sender: UIButton?) {
print("Center Tapped")
}
#objc func contextMenuButtonAction(_ sender: UIButton?) {
print("Context Menu Tapped")
// IF I am past blur effect here and some action for diffent VC nothing happens but each time I'll saw printed text above)
}
}
This is image of menu which I am create but I am write code each time for each VC
Menu have ... when I press on it I am show the same animation for all VC and add some others view BUT When I am closed others sub view I am want implement different action depend of VC where menu did be opened.
Did you tried making one controller as base controller that can be inherited by all child controller and the common actions/activites to be part of that controller. Or maybe using a container view for child controller so that you can inherit properties of your base controller to your child controller.It depends on whatever suits your actual requirements

Textfield - Label - Button Answers according to inputs

I am very new to programming. But i am trying to improve myself and trying to what i am thinking. Here's my question.
I have 1 textfield 1 label and 1 button.
I want that when i write into the textfield for example "aaa" and press button i should see "bbb" in the label. This is first step. Actually i want to do this with some combinations. If i write "aaa bbb" and press button label must give me "ccc" as an answer. I know this is easy for you but stuck on it. I want all codes because as i said i am very new and try to myself by trying the codes for now.
Thank you in advance.
you add this code in your project.
step one:create textfield/label/button
step two:add button action
Code:
let textField = UITextField()
let label = UILabel()
let button = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() -> Void {
//1.textField
textField.frame = CGRect(x: 100, y: 100, width: 100, height: 50)
textField.placeholder = "enter.."
textField.backgroundColor = UIColor.brown
view.addSubview(textField)
//2.label
label.frame = CGRect(x: 100, y: 200, width: 100, height: 50)
label.textColor = UIColor.black
label.backgroundColor = UIColor.blue
view.addSubview(label)
//3.button
button.frame = CGRect(x: 100, y: 300, width: 100, height: 50)
button.setTitle("button", for: .normal)
button.backgroundColor = UIColor.brown
button.addTarget(self, action: #selector(buttonDidTouch), for: .touchUpInside)
view.addSubview(button)
}
func buttonDidTouch() -> Void {
label.text = "ccc"
}
You may see the screenshot. I know I expect all the codes from you but i need to get the logic in this way. Thank you again.

How to create a UIButton programmatically

I am trying to build UIViews programmatically. How do I get a UIButton with an action function in Swift?
The following code does not get any action:
let btn: UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
btn.backgroundColor = UIColor.greenColor()
btn.setTitle("Click Me", forState: UIControlState.Normal)
btn.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(buttonPuzzle)
The following selector function is:
func buttonAction(sender: UIButton!) {
var btnsendtag: UIButton = sender
}
You're just missing which UIButton this is. To compensate for this, change its tag property.
Here is you answer:
let btn: UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
btn.backgroundColor = UIColor.greenColor()
btn.setTitle("Click Me", forState: UIControlState.Normal)
btn.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
btn.tag = 1 // change tag property
self.view.addSubview(btn) // add to view as subview
Swift 3.0
let btn: UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
btn.backgroundColor = UIColor.green
btn.setTitle(title: "Click Me", for: .normal)
btn.addTarget(self, action: #selector(buttonAction), forControlEvents: .touchUpInside)
btn.tag = 1
self.view.addSubview(btn)
Here is an example selector function:
func buttonAction(sender: UIButton!) {
var btnsendtag: UIButton = sender
if btnsendtag.tag == 1 {
//do anything here
}
}
Using a tag is a fragile solution. You have a view and you are creating and adding the button to that view, you just need to keep a reference to it: For example
In your class, keep a reference to the button
var customButton: UIButton!
Create the button and set the reference
let btn = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
btn.backgroundColor = .greenColor()
btn.setTitle("Click Me", forState: .Normal)
btn.addTarget(self, action: #selector(MyClass.buttonAction), forControlEvents: .TouchUpInside)
self.view.addSubview(btn)
customButton = btn
Test against this instance in the action function
func buttonAction(sender: UIButton!) {
guard sender == customButton else { return }
// Do anything you actually want to do here
}
You have to addSubview and tag on that btn.