Removing a UILabel programmatically after a button is pressed - swift

I am trying to create/show a label when a button is pressed, and then delete/hide the same label when the same button is pressed again. I am trying to do this all programmatically in Swift.
I have tried using label.removeFromSuperview() but it doesn't seem to have any effect. However when i try removing the button in the same code location using button.removeFromSuperview()
var label = UILabel()
let labelImage = UIImage(named: "Strike Line.png")
/* to select checkmarked state */
func pressCheck() {
let image = UIImage(named: "Checkmark.png")
button.setBackgroundImage(image, for: UIControlState.normal)
button.addTarget(self, action:#selector(self.pressUnCheck), for: .touchUpInside)
self.view.addSubview(button)
textField1.textColor = UIColor.gray //change textfield to a gray color
label = UILabel(frame: CGRect(x : 31, y : 69, width: 200, height: 2))
label.backgroundColor = UIColor(patternImage: labelImage!)
self.view.addSubview(label)
}
func pressUnCheck()
{
let image = UIImage(named: "To Be Completed Circle.png")
button.setBackgroundImage(image, for: UIControlState.normal)
button.addTarget(self, action:#selector(self.pressCheck), for: .touchUpInside)
self.view.addSubview(button)
label.removeFromSuperview()
textField1.textColor = UIColor.black
}
Here is where i am trying to remove/hide the label.

Since this apparently was the fix I'll drop it in as an answer.
Add button.removeTarget(nil, action: nil, for: .allEvents) before you add any new targets to your button.
If you don't remove the current target it'll have multiple targets and be calling both pressCheck() and pressUnCheck() on each button press.

There's a few ways to handle this... If you just want to hide it you can use
label.isHidden = true - would hide the label.
label.isHidden = false - would show the label.

Related

Accessory view on UITextField

I created a textfield and a button for the eye.
The privacy eye is superimposed on the password when it reaches more than 35 characters.
Do you have any idea how to solve this problem? here is my code for the button
public var pincodeVisibilityButton: UIButton = {
let button = UIButton()
button.setTitleColor(.SEBlack, for: .normal)
button.titleLabel?.font = UIFont.icon(ofSize: 34)
button.translatesAutoresizingMaskIntoConstraints = false
button.isUserInteractionEnabled = true
return button
}()
It is best to use built in functionality.
Reference: https://developer.apple.com/documentation/uikit/uitextfield
Sample code is below:
let overlayButton = UIButton(type: .custom)
let bookmarkImage = UIImage(systemName: "bookmark")
overlayButton.setImage(bookmarkImage, for: .normal)
overlayButton.addTarget(self, action: #selector(displayBookmarks),
for: .touchUpInside)
overlayButton.sizeToFit()
// Assign the overlay button to the text field
textField.rightView = overlayButton
textField.rightViewMode = .always
Refer:

Button subtitle label

One day i did button with title label, subtitle label and image in storyboard and got this effect
Image of button in storyboard
but now when i am trying to do this in code programmly i have a problem, i dont see subtitle..
private var firstPaidPack: UIButton = {
let button = UIButton(type: .custom)
let image = UIImage(systemName: "circle")
button.layer.cornerRadius = 15
button.backgroundColor = UIColor(white: 1, alpha: 0.3)
button.setImage(image, for: .normal)
button.setTitle("1.99$", for: .normal)
button.subtitleLabel?.textAlignment = .center
button.subtitleLabel?.text = "subtitle text to check how it..."
button.titleLabel?.font = UIFont(name: "Arial", size: screenWidth / 375 * 19)
return button
}()
You need to create a UIButton.Configuration and set the subtitle on the configuration object:
var config = UIButton.Configuration.tinted()
config.subtitle = "subtitle text to check how it..."
// Set title and all other properties on the configuration object...
let button = UIButton(type: .custom)
button.configuration = config
You can also set the title and all other properties on the configuration object instead.
Try the below tricks will help you to change the subtitle of the button.
if #available(iOS 15.0, *) {
button.configuration?.subtitle = "Your Subtitle"
}
Have a look here for a detailed answer.

Evenly space UIToolbar buttons in inputAccessoryView

In the following code I have three buttons that show when an inputField is tapped. Right now the buttons show but all of them are shifted to the left and what I would like to do is have them evenly space and keep them like that regardless of what phone size they are viewed on.
How can I evenly space the buttons in a UIToolbar?
CODE:
override func viewDidLoad() {
super.viewDidLoad()
addButtonsToKeyboard()
}
// Reusable Button
func configurButton(button:UIButton) {
button.backgroundColor = UIColor.whiteColor()
button.layer.cornerRadius = 5
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor.blueColor().CGColor
button.setTitleColor(UIColor.lightGrayColor(), forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Highlighted)
button.frame = CGRect(x:0, y:0, width:50, height:35)
button.addTarget(self, action: #selector(customKeyPressed), forControlEvents: UIControlEvents.TouchUpInside)
}
func addButtonsToKeyboard(){
// First button
let button1 = UIButton()
button1.setTitle("Btn 1", forState: .Normal)
configureButton(button1)
let barButton1 = UIBarButtonItem()
barButton1.customView = button1
// Second button
let button2 = UIButton()
button2.setTitle("Btn 2", forState: .Normal)
configureButton(button2)
let barButton2 = UIBarButtonItem()
barButton2.customView = button2
// Third button
let button3 = UIButton()
button3.setTitle("Btn 3", forState: .Normal)
configureButton(button3)
let barButton3 = UIBarButtonItem()
barButton3.customView = button3
/**
* UIToolbar.
*/
let toolBar = UIToolbar()
toolBar.tintColor = UIColor.redColor()
toolBar.barTintColor = UIColor.lightGrayColor()
toolBar.items = [barButton1, barButton2, barButton3]
toolBar.sizeToFit()
myInputField.inputAccessoryView = toolBar
}
func customKeyPressed(sender: UIButton){
// do something
}
CURRENT:
AFTER:
Very simple, you just need to add a flexible bar button item between each button. See the following:
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolbar.items = [barButton1, space, barButton2, space, barButton3]

How to scale image and center it on a UIButton in Swift?

var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
var image = UIImage(named: "myimage.png") as UIImage!
button.frame = CGRectMake(0, 0, 100, 100)
button.setImage(image, forState: .Normal)
I have an image that I've set on my button, but I'd like to scale it to be smaller than the button (for example the image should be 50,50) and center in the button. How might I do this in Swift?
Xcode 8.3.1 • Swift 3.1
let button = UIButton(type: .custom)
let image = UIImage(named: "myimage.png")
func buttonTouchDown(_ button: UIButton) {
print("button Touch Down")
}
override func viewDidLoad() {
super.viewDidLoad()
button.frame = CGRect(x: 0, y: 0 , width: 100, height: 100)
button.backgroundColor = .clear
button.addTarget(self, action: #selector(buttonTouchDown), for: .touchDown)
button.setTitle("Title", for: .normal)
button.setTitleColor(.black, for: .normal)
button.setImage(image, for: .normal)
button.imageEdgeInsets = UIEdgeInsetsMake(25,25,25,25)
view.addSubview(button)
}
Swift 5, Swift 4, Swift 3
var image = UIImage(named: "myimage") as UIImage!
btnetc.setImage(image, for: .normal)
btnetc.imageView?.contentMode = .scaleAspectFill
or
btnetc.imageView?.contentMode = .scaleAspectFit
or
btnetc.imageView?.contentMode = .scaleToFill
Ther is a much easier way to do this where you don't have to deal with content insets. Here its is:
var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
var image = UIImage(named: "myimage.png") as UIImage!
button.frame = CGRectMake(0, 0, 100, 100)
button.setImage(image, forState: .Normal)
button.contentMode = .center
button.imageView?.contentMode = .scaleAspectFit
Or via XIB after selecting your UIButton.
Just make sure your insets are all the same.
Xcode 13, Swift 5
Using storyboard, select the button, then in the size inspect click the dropdown on size just above Content inset. There is a list of sizes to select from, and this will adjust your image size(if you use system image). The default size is already set when you added the button on the storyboard to the View Controller.

Swift- How to Display Image over Button?

I'm trying to display an Image over a button, I'm getting BLUE PRINT of Image over button, I have tried so far this-
override func viewDidLoad()
{
super.viewDidLoad()
var birdTexture1 = UIImage(named: "fish.png") as UIImage
button1.frame = CGRectMake(100, 10, 50, 150)
button1.setImage(birdTexture1, forState: .Normal)
button1.setTitle("Testing", forState: UIControlState.Normal)
button1.addTarget(self, action: "btnAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button1)
// Do any additional setup after loading the view, typically from a nib.
}
By above code, I m getting, the following output
But the Actual Image is this-
I think your UIButton needs to be of type UIButtonTypeCustom, rather than UIButtonTypeSystem. You either constructed it as such, or need to update the UIButton's properties in interface builder.
More info: https://developer.apple.com/library/ios/documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/occ/clm/UIButton/buttonWithType:
i think replace this code:
let birdTexture1 = UIImage(named: "fish.png")! as UIImage
let button1:UIButton=UIButton(frame:CGRectMake(100, 50, 50, 150))
button1.setBackgroundImage(birdTexture1, forState: .Normal)
button1.setTitle("Testing", forState: .Normal)
button1.addTarget(self, action: #selector(ViewController.btnActionClick(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button1)
#IBAction func btnActionClick(sender:AnyObject){
}
and also add to image in target