Remove clear button on clicking any other field or anywhere - ios

I managed to show a custom clearbutton, the problem is that it will not be removed when clicking anywhere else or clicking other textfield. It is always showing.
Here is my extension:
extension UITextField {
func clearButtonWithImage(_ image: UIImage) {
let clearButton = UIButton()
clearButton.setImage(image, for: .normal)
clearButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
clearButton.contentMode = .scaleAspectFit
clearButton.addTarget(self, action: #selector(self.clear(sender:)), for: .touchUpInside)
self.rightView = clearButton
self.rightViewMode = .always
}
func clear(sender: AnyObject) {
self.text = ""
}
}
and here i show the clearbutton on the method:
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField == dateSearchTextField {
self.performSegue(withIdentifier: "showCalendar", sender: self)
textField.clearButtonWithImage(#imageLiteral(resourceName: "icClear"))
return false
} else if textField == timeSearchTextField {
self.performSegue(withIdentifier: "showTimePicker", sender: self)
textField.clearButtonWithImage(#imageLiteral(resourceName: "icClear"))
return false
}
return true
}
I want it to be visible only when clicking inside the textfield.

Replace this:
self.rightViewMode = .always
With:
self.rightViewMode = .whileEditing

Related

How to exit keyboard on tap outside of uitextfield or button

I need to be able to tap out of the keyboard when not tapping in uitextfield or when not tapping show/hide password button.
I was previously using this code to do that:
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
}
But the problem with that was that it clicks out of the keyboard even when clicking the show/hide password eye icon. The code I'm using for the show/hide icon is this:
extension UITextField {
func showhidepasswordbutton(image: UIImage = UIImage(systemName: "eye.slash")!) {
let button = UIButton(type: .custom)
button.setImage(image, for: .normal)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -16, bottom: 0, right: 0)
button.frame = CGRect(x: CGFloat(self.frame.size.width - 25), y: CGFloat(5), width: CGFloat(25), height: CGFloat(25))
button.addTarget(self, action: #selector(self.refreshforshowhide), for: .touchUpInside)
button.tintColor = .darkGray
self.rightView = button
self.rightViewMode = .always
}
#IBAction func refreshforshowhide(_ sender: Any) {
print("ok")
if self.isSecureTextEntry == true {
self.togglePasswordVisibility()
showhidepasswordbutton(image: UIImage(systemName: "eye")!)
} else if self.isSecureTextEntry == false {
self.togglePasswordVisibility()
showhidepasswordbutton(image: UIImage(systemName: "eye.slash")!)
}
}
func togglePasswordVisibility() {
let temptext = self.text
isSecureTextEntry.toggle()
self.text = ""
self.text = temptext
}
}
Sorry for the messy code, just wrote the show/hide password code up.
You could exclude the taps on subviews using gestureRecognizer(_:, shouldReceive:) method in UIGestureRecognizerDelegate.
extension UIViewController: UIGestureRecognizerDelegate {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
tap.delegate = self
view.addGestureRecognizer(tap)
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
touch.view?.isDescendant(of: view) == false // will return false if touch was received by a subview
}
}
Update: You could use touch.view == view instead of touch.view?.isDescendant(of: view) == false.

Question about disabling one button when one button is active in Swift

The picture above has two buttons.
The background is filled in red with the left button pressed.
If I press right button here
I want the background of the right button to be filled with red, the left button to be white as the right button, and the button to be deactivated.
override func viewDidLoad() {
super.viewDidLoad()
bookTitleFilterBtn.addTarget(self, action: #selector(bookTitleFilterBtnClicked(_:)), for: .touchUpInside)
authorNameFilterBtn.addTarget(self, action: #selector(authorNameFilterBtnClicked(_:)), for: .touchUpInside)
}
//left button
#objc func bookTitleFilterBtnClicked(_ sender: UIButton) {
DispatchQueue.main.async {
if self.isHighlighted == false {
sender.backgroundColor = .red
let title = NSAttributedString(string: "제목", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
sender.setAttributedTitle(title, for: .normal)
sender.isHighlighted = true
self.isHighlighted = true
} else {
sender.backgroundColor = .white
let title = NSAttributedString(string: "제목", attributes: [NSAttributedString.Key.foregroundColor: UIColor.black])
sender.setAttributedTitle(title, for: .normal)
sender.isHighlighted = false
self.isHighlighted = false
}
}
}
//right button
#objc func authorNameFilterBtnClicked(_ sender: UIButton) {
DispatchQueue.main.async {
if self.isHighlighted == false {
sender.isHighlighted = true
let title = NSAttributedString(string: "작가", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
sender.setAttributedTitle(title, for: .normal)
sender.backgroundColor = .red
self.isHighlighted = true
} else {
sender.isHighlighted = false
self.isHighlighted = false
let title = NSAttributedString(string: "작가", attributes: [NSAttributedString.Key.foregroundColor: UIColor.black])
sender.setAttributedTitle(title, for: .normal)
sender.backgroundColor = .white
}
}
}
You forgot to change the backgroundColor in the first condition of the first method. To prevent more of these kind of issues, try to define the logic in a function and call it anywhere you need instead of rewriting it over and over:
override func viewDidLoad() {
super.viewDidLoad()
bookTitleFilterBtn.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
authorNameFilterBtn.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
}
var buttons: [UIButton] { return [bookTitleFilterBtn, authorNameFilterBtn] }
func updateButtonsAppearance(allButtons: [UIButton], selectedButton: UIButton) {
for button in allButtons {
let isSelected = button == selectedButton
let currentTitle = button.currentTitle ?? "-"
let title = NSAttributedString(string: currentTitle, attributes: [.foregroundColor: isSelected ? UIColor.white : UIColor.black])
button.setAttributedTitle(title, for: .normal)
button.backgroundColor = isSelected ? .red : .white
button.isHighlighted = isSelected
}
}
#objc func buttonClicked(_ sender: UIButton) {
DispatchQueue.main.async {
self.updateButtonsAppearance(allButtons: buttons, selectedButton: sender)
}
}
Note that both buttons are now calling same function. So there is only one source of truth now. If it works somewhere, it works everywhere.
You are missing following line of code to change backgroundColor of another button. Add following line of code.
//left button
#objc func bookTitleFilterBtnClicked(_ sender: UIButton) {
DispatchQueue.main.async {
if self.isHighlighted == false {
....
....
authorNameFilterBtn.backgroundColor = .white
} else {
....
}
}
}
//right button
#objc func authorNameFilterBtnClicked(_ sender: UIButton) {
DispatchQueue.main.async {
if self.isHighlighted == false {
....
bookTitleFilterBtn.backgroundColor = .white
} else {
....
}
}
}
This code will change color of buttons vice-versa
set left button default selected from StoryBoard
var selectedButton:String = "" // gloable variable
//left button
#objc func bookTitleFilterBtnClicked(_ sender: UIButton) {
if selectedButton != "제목"
{
selectedButton = "제목"
sender.backgroundColor = .red
let title = NSAttributedString(string: "제목", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])//title
sender.setAttributedTitle(title, for: .normal)
sender.isHighlighted = true
self.isHighlighted = true
authorNameFilterBtn.backgroundColor = .white
let title1 = NSAttributedString(string: "작가", attributes: [NSAttributedString.Key.foregroundColor: UIColor.black])//title
authorNameFilterBtn.setAttributedTitle(title1, for: .normal)
authorNameFilterBtn.isHighlighted = false
self.isHighlighted = false
}
}
//right button
#objc func authorNameFilterBtnClicked(_ sender: UIButton) {
if selectedButton != "작가"
{
selectedButton = "작가"
sender.isHighlighted = true
let title = NSAttributedString(string: "작가", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])//Author
sender.setAttributedTitle(title, for: .normal)
sender.backgroundColor = .red
self.isHighlighted = true
bookTitleFilterBtn.isHighlighted = false
self.isHighlighted = false
let title1 = NSAttributedString(string: "제목", attributes: [NSAttributedString.Key.foregroundColor: UIColor.black])
bookTitleFilterBtn.setAttributedTitle(title1, for: .normal)
bookTitleFilterBtn.backgroundColor = .white
}

Only allow button click if username and password text fields are filled in - IOS (Login page)

How do I go about allowing my login button to be clicked only if the username and password text fields have been filled in?
Ideally the login button would be grayed out and un-clickable, only becoming fully functional once all fields have been filled in.
I'm very new to iOS development, so I am also unsure if I'd need to do anything regarding the "UITextFieldDelegate", would that be an important aspect here?
import UIKit
class LoginController: UIViewController {
// Creating text fields
let emailTF: UITextField = {
let e = UITextField()
let attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
e.attributedPlaceholder = attributedPlaceholder
e.textColor = .white
e.keyboardType = UIKeyboardType.emailAddress
e.setBottomBorder(backgroundColor: ORANGE_COLOR, borderColor: .white)
return e
}()
let passwordTF: UITextField = {
let p = UITextField()
let attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
p.attributedPlaceholder = attributedPlaceholder
p.textColor = .white
p.setBottomBorder(backgroundColor: ORANGE_COLOR, borderColor: .white)
p.isSecureTextEntry = true
return p
}()
// Creating buttons
let loginButton: UIButton = {
let l = UIButton(type: .system)
l.setTitleColor(.white, for: .normal)
l.setTitle("Log In", for: .normal)
l.backgroundColor = UIColor.rgb(r: 89, g: 156, b: 120)
l.layer.cornerRadius = 25
return l
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.isNavigationBarHidden = true
view.backgroundColor = ORANGE_COLOR
setupTextFields()
setupLoginButton()
}
override var preferredStatusBarStyle: UIStatusBarStyle{
return .lightContent
}
// Text Field Setup Functions
fileprivate func setupTextFields() {
setupEmailTF()
setupPasswordTF()
}
fileprivate func setupEmailTF() {
view.addSubview(emailTF)
emailTF.anchors(top: nil, topPad: 0, bottom: nil, bottomPad: 0, left: view.leftAnchor, leftPad: 24, right: view.rightAnchor, rightPad: 24, height: 30, width: nil)
emailTF.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
fileprivate func setupPasswordTF() {
view.addSubview(passwordTF)
passwordTF.anchors(top: emailTF.bottomAnchor, topPad: CGFloat(TEXT_FIELD_SPACING), bottom: nil, bottomPad: 0, left: emailTF.leftAnchor, leftPad: 0, right: emailTF.rightAnchor, rightPad: 0, height: 30, width: nil)
}
// Button Setup Functions
fileprivate func setupLoginButton() {
view.addSubview(loginButton)
loginButton.anchors(top: passwordTF.bottomAnchor, topPad: CGFloat(TEXT_FIELD_SPACING * 2), bottom: nil, bottomPad: 0, left: passwordTF.leftAnchor, leftPad: 0, right: passwordTF.rightAnchor, rightPad: 0, height: 50, width: nil)
}
}
You should be handling this in editingChanged. You want it the changes to be reflected ideally every time the user makes a change in the textField. So change your UITextField definition like this:
let emailTF: UITextField = {
let e = UITextField()
let attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
e.attributedPlaceholder = attributedPlaceholder
e.textColor = .white
e.keyboardType = UIKeyboardType.emailAddress
e.setBottomBorder(backgroundColor: ORANGE_COLOR, borderColor: .white)
e.addTarget(self, action: #selector(editingChanged(_:)), for: .editingChanged) // <- Add this line
return e
}()
let passwordTF: UITextField = {
let p = UITextField()
let attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
p.attributedPlaceholder = attributedPlaceholder
p.textColor = .white
p.setBottomBorder(backgroundColor: ORANGE_COLOR, borderColor: .white)
p.addTarget(self, action: #selector(editingChanged(_:)), for: .editingChanged) // <- Add this line
p.isSecureTextEntry = true
return p
}()
//Handle button changes in this method
#objc func editingChanged(_ sender: UITextField) {
if !emailTF.text?.isEmpty || !passwordTF.text?.isEmpty {
button.isEnabled = false
//Do highlighting changes to show disabled state
} else {
button.isEnabled = true
//Undo highlighting changes
}
}
Edit: Since both textFields' would be empty in the begnning, i also suggest you disable the button in viewDidLoad.
func viewDidLoad() {
super.viewDidLoad()
//Do other viewDidLoad stuff
button.isEnabled = false
}
Or you could implement the didBeginEditing delegate and set emailTF as first responder as soon as the view is loaded.
func viewDidLoad() {
super.viewDidLoad()
//Do other viewDidLoad stuff
emailTF.becomeFirstResponder()
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if !emailTF.text?.isEmpty || !passwordTF.text?.isEmpty {
button.isEnabled = false
//Do highlighting changes to show disabled state
} else {
button.isEnabled = true
//Undo highlighting changes
}
}
Here is a simple way to do this:
1. Listen delegate textFieldDidBeginEditing:
2. Inside this method you check length of emailTF and passwordTF, if both of them have length > 0, then enable button, else disable it.
Try to implement this code, hope this helps.
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.isNavigationBarHidden = true
view.backgroundColor = ORANGE_COLOR
setupTextFields()
setupLoginButton()
emailTF.delegate = self
passwordTF.delegate = self
}
//Textfield delegate
func textFieldDidEndEditing(textField: UITextField) {
if emailTF.text?.count > 0 && passwordTF.text?.count >0{
loginButton.enabled = true
loginButton.alpha = 1.0
} else {
loginButton.enabled = false
loginButton.alpha = 0.5
}
}
// Button Setup Functions
fileprivate func setupLoginButton() {
view.addSubview(loginButton)
loginButton.anchors(top: passwordTF.bottomAnchor, topPad:
CGFloat(TEXT_FIELD_SPACING * 2), bottom: nil, bottomPad: 0, left:
passwordTF.leftAnchor, leftPad: 0, right: passwordTF.rightAnchor, rightPad:
0, height: 50, width: nil)
loginButton.enabled = false
loginButton.alpha = 0.5
}

Subview loads but none of buttons work ios swift

I have a custom keyboard project with a Storyboard containing a collectionView and a scrollView. I also have a textField for a search bar that pulls up a nib containing a keyboard layout that I can use to search within the keyboard. When the subview containing the keyboard becomes active, I cannot press any of the buttons. I have tried bringing the subView to front upon becoming active and have tried sending the main view to the back when hiding the collectionView. What can I do to use the buttons in the subview?
Before viewDidLoad
let filename = "buttonClick"
let ext = "m4a"
var soundId: SystemSoundID = 0
#objc func typeKey(sender : UIButton)
{
AudioServicesPlaySystemSound(soundId)
self.key.txtSearch.text = "\(self.key.txtSearch.text!)\((sender.titleLabel?.text!)!)"
if(self.key.txtSearch.text != "")
{
isCaps = false
updateKeyBoard()
}
}
#objc func typeSpaceKey(sender : UIButton)
{
AudioServicesPlaySystemSound(soundId)
self.key.txtSearch.text = "\(self.key.txtSearch.text!) "
}
#objc func typeDoneKey(sender : UIButton)
{
AudioServicesPlaySystemSound(soundId)
hideTextField()
}
#objc func typeNumKey(sender : UIButton)
{
AudioServicesPlaySystemSound(soundId)
isNum = !isNum
updateKeyBoard()
// self.key.txtSearch.text = "\(self.key.txtSearch.text!)\((sender.titleLabel?.text!)!)"
}
#objc func typeBackSpaceKey(sender : UIButton)
{
AudioServicesPlaySystemSound(soundId)
self.key.txtSearch.text = "\(self.key.txtSearch.text!.dropLast())"
if(self.key.txtSearch.text == "")
{
isCaps = true
updateKeyBoard()
}
}
#objc func typeCapsKey(sender : UIButton)
{
AudioServicesPlaySystemSound(soundId)
if(isNum)
{
isFirst = !isFirst
}
else
{
isCaps = !isCaps
}
updateKeyBoard()
}
#objc func updateKeyBoard()
{
if(isCaps)
{
self.key.btnCap.setImage(#imageLiteral(resourceName: "cap_F"), for: .normal)
}
else
{
self.key.btnCap.setImage(#imageLiteral(resourceName: "caps"), for: .normal)
}
var count = 0
for btn in buttons
{
if(!isNum)
{
if(isCaps)
{
btn.setTitle("\(arrCapOn[count])", for: .normal)
}
else
{
btn.setTitle("\(arrCapOff[count])", for: .normal)
}
}
else
{
if(isFirst)
{
btn.setTitle("\(arrNumCapOn[count])", for: .normal)
}
else
{
btn.setTitle("\(arrNumCapOff[count])", for: .normal)
}
}
count = count + 1
}
}
#objc func activeTextField()
{
self.key.btnBack.isHidden = false
self.key.txtSearch.becomeFirstResponder()
self.key.constLeftAchor.constant = 40
self.key.constSideKeyboard.constant = 8
self.key.constLeftAchorView.constant = 32
UIView.animate(withDuration: 0.2) {
self.key.viewKeyboard.transform = CGAffineTransform(translationX: 0, y: 0)
self.key.btnBack.alpha = 1.0
self.key.layoutIfNeeded()
}
self.key.btnTextFieldSelect.isHidden = true
}
#objc func hideTextField()
{
self.key.btnBack.isHidden = true
self.key.txtSearch.resignFirstResponder()
self.key.btnTextFieldSelect.isHidden = false
self.key.constSideKeyboard.constant = 400
self.key.constLeftAchor.constant = 24
self.key.constLeftAchorView.constant = 16
UIView.animate(withDuration: 0.2) {
self.key.viewKeyboard.transform = CGAffineTransform(translationX: self.view.frame.width, y: 0)
self.key.btnBack.alpha = 0.0
self.key.layoutIfNeeded()
}
}
#objc func hideArticles(){
self.categoriesScrollView.isHidden = true
self.collectionview.isHidden = true
//self.collectionview.isUserInteractionEnabled = false
//self.view.bringSubview(toFront: key)
//self.key.isUserInteractionEnabled = true
}
#objc func showArticles(){
self.categoriesScrollView.isHidden = false
self.collectionview.isHidden = false
}
#objc func handleTap(_ sender: UITapGestureRecognizer) {
self.key.txtSearch.text = "Hello"
self.inputView?.resignFirstResponder()
print("Hello World")
}
func textFieldDidBeginEditing(_ textField: UITextField) {
}
override func textWillChange(_ textInput: UITextInput?) {
// The app is about to change the document's contents. Perform any preparation here.
}
override func textDidChange(_ textInput: UITextInput?) {
// The app has just changed the document's contents, the document context has been updated.
var textColor: UIColor
let proxy = self.textDocumentProxy
if proxy.keyboardAppearance == UIKeyboardAppearance.dark {
textColor = UIColor.white
} else {
textColor = UIColor.black
}
// self.nextKeyboardButton.setTitleColor(textColor, for: [])
}
after viewDidLoad
if let soundUrl = Bundle.main.url(forResource: filename, withExtension: ext) {
AudioServicesCreateSystemSoundID(soundUrl as CFURL, &soundId)
}
self.key = Bundle.main.loadNibNamed("keyboard", owner: nil, options: nil)![0] as! keyboard
self.key.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 160)
//self.key.txtSearch.isUserInteractionEnabled = false
self.key.constLeftAchor.constant = 24
// self.key.viewKeyboard.transform = CGAffineTransform(translationX: self.view.frame.width, y: 0)
self.key.btnBack.isHidden = true
self.key.btnBack.alpha = 0.0
self.key.btnTextFieldSelect.addTarget(self, action: #selector(activeTextField), for: .touchUpInside)
self.key.btnTextFieldSelect.addTarget(self, action: #selector(hideArticles), for: .touchUpInside)
self.key.btnBack.addTarget(self, action: #selector(hideTextField), for: .touchUpInside)
self.key.btnBack.addTarget(self, action: #selector(showArticles), for: .touchUpInside)
buttons.append(self.key.btnQ)
buttons.append(self.key.btnW)
buttons.append(self.key.btnE)
buttons.append(self.key.btnR)
buttons.append(self.key.btnT)
buttons.append(self.key.btnY)
buttons.append(self.key.btnU)
buttons.append(self.key.btnI)
buttons.append(self.key.btnO)
buttons.append(self.key.btnP)
buttons.append(self.key.btnA)
buttons.append(self.key.btnS)
buttons.append(self.key.btnD)
buttons.append(self.key.btnF)
buttons.append(self.key.btnG)
buttons.append(self.key.btnH)
buttons.append(self.key.btnJ)
buttons.append(self.key.btnK)
buttons.append(self.key.btnL)
buttons.append(self.key.btnZ)
buttons.append(self.key.btnX)
buttons.append(self.key.btnC)
buttons.append(self.key.btnV)
buttons.append(self.key.btnB)
buttons.append(self.key.btnN)
buttons.append(self.key.btnM)
for btn in buttons
{
btn.addTarget(self, action: #selector(typeKey), for: .touchUpInside)
}
self.key.btnCap.addTarget(self, action: #selector(typeCapsKey), for: .touchUpInside)
self.key.btnBackSpace.addTarget(self, action: #selector(typeBackSpaceKey), for: .touchUpInside)
self.key.btnSpace.addTarget(self, action: #selector(typeSpaceKey), for: .touchUpInside)
self.key.btnDone.addTarget(self, action: #selector(typeDoneKey), for: .touchUpInside)
//self.key.btnDone.addTarget(self, action: #selector(fetchSearch), for: .touchUpInside)
self.key.btnNum.addTarget(self, action: #selector(typeNumKey), for: .touchUpInside)
view.addSubview(key)
activeTextField()
hideTextField()
Please make sure the added subviews are userinteration enabled and it is not send to back in superview.

Image for UIControlState.Selected does not appear

The title says it all. Here is my code:
func createCheckBoxButton(xPos: CGFloat, yPos: CGFloat, tag: Int) -> UIButton {
var checkBox = UIButton(frame: CGRect(x: xPos, y: yPos, width: checkBoxSize, height: checkBoxSize))
checkBox.setBackgroundImage(UIImage(named: "checkbox_inactive"), forState: UIControlState.Normal)
checkBox.setBackgroundImage(UIImage(named: "checkbox_pressed"), forState: UIControlState.Highlighted)
checkBox.setBackgroundImage(UIImage(named: "checkbox_active"), forState: UIControlState.Selected)
checkBox.tag = tag
checkBox.contentMode = .ScaleAspectFit
checkBox.addTarget(self, action: "processButton:", forControlEvents: UIControlEvents.TouchUpInside)
return checkBox
}
And there is the called function when my button is pressed:
func processButton(sender: UIButton) {
if (answerViewArray[sender.tag].backgroundColor == UIColor.whiteColor()) {
answerViewArray[sender.tag].backgroundColor = myColor.pinky()
} else {
answerViewArray[sender.tag].backgroundColor = UIColor.whiteColor()
}
let tag = answerButtonsArray[sender.tag]
answer.buttonPressed(tag)
}
When I launch the app, the checkbox_inactive image is there. When I press and keep it pressed, the checkbox_pressed image appears. But when I release my click the checkbox_inactive appears again instead of checkbox_active.
I also tried with an UIImageView, which would be the best solution for me actually. I set my checkbox as an UIImageView and at the top of my general view I put an invisible view so I can click everywhere. But when I press my invisible view, the UIImageView simply disappears.
Here is the code:
func createCheckBoxButton(xPos: CGFloat, yPos: CGFloat) -> UIImageView {
var checkBox = UIImageView(frame: CGRect(x: xPos, y: yPos, width: checkBoxSize, height: checkBoxSize))
checkBox.image = UIImage(named: "checkbox_inactive")
checkBox.contentMode = .ScaleAspectFit
return checkBox
}
Here is the function called:
func processButton(sender: UIButton) {
if (answerViewArray[sender.tag].backgroundColor == UIColor.whiteColor()) {
answerViewArray[sender.tag].backgroundColor = myColor.pinky()
checkBoxArray[sender.tag].image = UIImage(named: "checkbox-active")
} else {
answerViewArray[sender.tag].backgroundColor = UIColor.whiteColor()
checkBoxArray[sender.tag].image = UIImage(named: "checkbox-inactive")
}
let tag = answerButtonsArray[sender.tag]
answer.buttonPressed(tag)
}
To make appear checkbox_active when you release your button you should make selected=true for the pressed button.
So your function should be like:
func processButton(sender: UIButton) {
// If button not selected
if(sender.selected==false){
sender.selected = true;
}
else{ // If button already selected
sender.selected = false;
}
// Do your other stuff
}

Resources