UIbutton background colour and button enable/disable - swift3

How can we set a hex value to the background of button value is #88D317? Also, I want to keep the button enabled only if there is text present in textfields, else disabled.
Here is the code I have written:
class ViewControllerDonarLogin: UIViewController, UITextFieldDelegate {
#IBOutlet var btnlogin: UIButton!
#IBOutlet weak var btn: UIButton!
#IBOutlet weak var textfieldpassword: UITextField!
#IBOutlet weak var textfieldusername: UITextField!
var alert : UIAlertController = UIAlertController()
var action : UIAlertAction = UIAlertAction()
override func viewDidLoad() {
super.viewDidLoad()
buttonborder()
btnlogin.backgroundColor = UIColor(red: 136/255, green: 211/255, blue: 23/255, alpha: 0.5)
if textfieldpassword.text == "" && textfieldusername.text == "" {
btnlogin.isEnabled = false
} else {
btnlogin.isEnabled = true
}
// Do any additional setup after loading the view.
}
}

You can use one of the text field's UIControl actions.
In viewDidLoad, add self as a target for editingChanged:
textfieldpassword.addTarget(self, action: #selector(textChanged), for: .editingChanged)
textfieldusername.addTarget(self, action: #selector(textChanged), for: .editingChanged)
Now, add this method:
func textChanged() {
// This will be called every time the text field's text changes
}
Move the original code you wrote in viewDidLoad to the above method.
if textfieldpassword.text == "" || textfieldusername.text == ""
{
btnlogin.isEnabled = false
}
else
{
btnlogin.isEnabled = true
}

What you want to achieve can be done by using text field delegates. You will have to use
func textFieldDidEndEditing(_ textField: UITextField) {
if textfieldpassword.text == "" || textfieldusername.text == "" {
btnlogin.isEnabled = false
} else {
btnlogin.isEnabled = true
}
}
also you will have to disable the button in viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
btnlogin.isEnabled = false // as you want button to be disabled at the starting
}

Related

SwiftUI: Always active textfield keyboard doesn't dismiss

I made a custom Textfield an always active textfield with the help of some tutorials, meaning that user can tap "next on keyboard" and commits the message and continue doing so without hiding the keyboard, but now the keyboard is stuck, doesn't close when tapped outside, I tried everything I saw online, some of them were basically triggering UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
Note: my minimum iOS requirements is iOS 14 which restricts some of the new functions that helps with my issue in iOS15.
that didn't work with that Custom Textfield, its like its overriding those functions.
here is the textfield code:
import SwiftUI
struct AlwaysActiveTextField: UIViewRepresentable {
let placeholder: String
#Binding var text: String
var focusable: Binding<[Bool]>?
var returnKeyType: UIReturnKeyType = .next
var autocapitalizationType: UITextAutocapitalizationType = .none
var keyboardType: UIKeyboardType = .default
var isSecureTextEntry: Bool
var tag: Int
var onCommit: () -> Void
func makeUIView(context: Context) -> UITextField {
let activeTextField = UITextField(frame: .zero)
activeTextField.delegate = context.coordinator
activeTextField.placeholder = placeholder
activeTextField.font = .systemFont(ofSize: 14)
activeTextField.attributedPlaceholder = NSAttributedString(
string: placeholder,
attributes: [NSAttributedString.Key.foregroundColor: UIColor(contentTertiary)]
)
activeTextField.returnKeyType = returnKeyType
activeTextField.autocapitalizationType = autocapitalizationType
activeTextField.keyboardType = keyboardType
activeTextField.isSecureTextEntry = isSecureTextEntry
activeTextField.textAlignment = .left
activeTextField.tag = tag
// toolbar
if keyboardType == .numberPad { // keyboard does not have next so add next button in the toolbar
var items = [UIBarButtonItem]()
let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let toolbar: UIToolbar = UIToolbar()
toolbar.sizeToFit()
let nextButton = UIBarButtonItem(title: "Next", style: .plain, target: context.coordinator, action: #selector(Coordinator.showNextTextField))
items.append(contentsOf: [spacer, nextButton])
toolbar.setItems(items, animated: false)
activeTextField.inputAccessoryView = toolbar
}
// Editin listener
activeTextField.addTarget(context.coordinator, action: #selector(Coordinator.textFieldDidChange(_:)), for: .editingChanged)
return activeTextField
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = text
if let focusable = focusable?.wrappedValue {
if focusable[uiView.tag] { // set focused
uiView.becomeFirstResponder()
} else { // remove keyboard
uiView.resignFirstResponder()
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
final class Coordinator: NSObject, UITextFieldDelegate {
let activeTextField: AlwaysActiveTextField
var hasEndedViaReturn = false
weak var textField: UITextField?
init(_ activeTextField: AlwaysActiveTextField) {
self.activeTextField = activeTextField
}
func textFieldDidBeginEditing(_ textField: UITextField) {
self.textField = textField
guard let textFieldCount = activeTextField.focusable?.wrappedValue.count else { return }
var focusable: [Bool] = Array(repeating: false, count: textFieldCount) // remove focus from all text field
focusable[textField.tag] = true // mark current textField focused
activeTextField.focusable?.wrappedValue = focusable
}
// work around for number pad
#objc
func showNextTextField() {
if let textField = self.textField {
_ = textFieldShouldReturn(textField)
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
hasEndedViaReturn = true
guard var focusable = activeTextField.focusable?.wrappedValue else {
textField.resignFirstResponder()
return true
}
focusable[textField.tag] = true // mark current textField focused
activeTextField.focusable?.wrappedValue = focusable
activeTextField.onCommit()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
if !hasEndedViaReturn {// user dismisses keyboard
guard let textFieldCount = activeTextField.focusable?.wrappedValue.count else { return }
// reset all text field, so that makeUIView cannot trigger keyboard
activeTextField.focusable?.wrappedValue = Array(repeating: false, count: textFieldCount)
} else {
hasEndedViaReturn = false
}
}
#objc
func textFieldDidChange(_ textField: UITextField) {
activeTextField.text = textField.text ?? ""
}
}
}
used it on sample SwiftUI Sheet view and inside the .sheet view:
AlwaysActiveTextField(
placeholder: "Add...",
text: $newItemName,
focusable: $fieldFocus,
returnKeyType: .next,
isSecureTextEntry: false,
tag: 0,
onCommit: {
if !newItemName.isEmpty {
let newChecklistItem = ChecklistItem(
shotId: shotlistViewModel.shot.id,
name: self.newItemName,
isChecked: false,
description: ""
)
self.checklistItems.append(newChecklistItem)
if !offlineMode {
self.viewModel.addChecklistItem(newChecklistItem)
}
self.newItemName = ""
}
}
)

Custom delegate is always nil

I have a problem with my delegate use in a protocol, many person face the same problem but no answer works for me.
My first class is FavorisHeaderTableView
import UIKit
protocol FavorisHeaderDelegate {
func changeFavoris(sender: FavorisHeaderTableViewCell)
}
class FavorisHeaderTableViewCell: UITableViewCell {
#IBOutlet weak var lblTitle: UILabel!
#IBOutlet weak var txtFavoriteNameInput: UITextField!
#IBOutlet weak var lblIcon: UILabel!
#IBOutlet weak var lblTime: UILabel!
#IBOutlet weak var lblDescription: UILabel!
#IBOutlet weak var btnFavHeart: UIButton!
#IBOutlet weak var btnFavHome: UIButton!
#IBOutlet weak var btnFavShop: UIButton!
#IBOutlet weak var btnFavWork: UIButton!
#IBOutlet weak var btnFavGolf: UIButton!
var myDelegate: FavorisHeaderDelegate? = nil
var defaultIcon:FavIconType = .heart
var selectedIcon:UIButton? = nil {
didSet {
selectedIcon!.backgroundColor = Design.Palette.red
selectedIcon?.layer.cornerRadius = 3
selectedIcon?.tintColor = Design.Palette.white
}
willSet {
if selectedIcon != nil {
selectedIcon!.backgroundColor = UIColor.clear
selectedIcon?.tintColor = UIColor(red:0.671, green:0.651, blue:0.635, alpha:1)
}
}
}
#IBAction func didSelectIcon(_ sender: UIButton) {
selectedIcon = sender
self.myDelegate?.changeFavoris(sender: self)
}
#IBAction func changeTitle(_ sender: Any) {
txtFavoriteNameInput.text = "gare centro"
print("delegate: ",myDelegate)
if myDelegate != nil {
myDelegate?.changeFavoris(sender: self)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
The second class who use the protocol is
addFavoriteViewController: UIViewController {
// MARK properties
let defaultLocalizer = AMPLocalizeUtils.defaultLocalizer
var favorisName:String? = nil
var defaultIcon:FavIconType = .heart
var delegate:handleFavorite? = nil
#IBOutlet weak var favTableView: UITableView!
var headerCell:FavorisHeaderTableViewCell?
override func viewDidLoad() {
super.viewDidLoad()
// Localization of labels
//lblAddToFavorite.text = defaultLocalizer.stringForKey(key: "str_favorites_addTitle")
//lblFavoriteName.text = defaultLocalizer.stringForKey(key: "str_favorites_nameInput")
favTableView.delegate = self
favTableView.dataSource = self
self.headerCell?.myDelegate = self
}
override func viewWillAppear(_ animated: Bool) {
// Text Field
//favorisName.clearButtonMode = .whileEditing
}
var place:PlaceModel? = nil
var itinerary:(source:PlaceModel, destination:PlaceModel)? = nil
let db = DataController.shared
var favorite:FavoritesMO? = nil
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension UGOaddFavoriteViewController: FavorisHeaderDelegate {
func changeFavoris(sender: FavorisHeaderTableViewCell) {
defaultIcon = sender.defaultIcon
favorisName = sender.txtFavoriteNameInput.text
}
}
When I try this code "myDelegate" is always nil and I don't understand what's wrong despite of all topic read about this problem.
You are setting self as the delegate of the wrong cell!
Here:
self.headerCell?.myDelegate = self
you set the headerCell's delegate to self, but headerCell is never actually displayed on the screen!
You need to actually set the delegates of the cells on the screen, not the delegate of a random cell that you created.
The best place to do this is cellForRowAtIndexPath:
let cell = tableView.dequeueResusableCell(withIdentifier:...)!
// configure your cell
cell.delegate = self // set the delegate here!

UserDefaults.standard not saving swift3 xcode 8

Hello everybody I'm trying to build a simple one view program to call and navigate a voice menu, I cannot get the UserDefaults to properly save between closing of the app. I've also had issue with getting text to display in the UITextField, I would like for it to display if saved on launch, here is a description of vars:
UserInput - text field for employee ID (what needs saving)
Switch - if Save it is 1 save data, if 0 do not
Submit - submit button that should save the data and call.
This is my first iPhone app and any help would be much appreciated!
enter code here
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var UserInput: UITextField!
var SaveIt = true
var employID = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.UserInput.delegate = self;
UserInput.keyboardType = .numberPad
if let current_eid = UserDefaults.standard.string(forKey: "emp_ID") {
UserInput.text = current_eid
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadDefaults() {
let defaults = UserDefaults.standard
if let UserInput = defaults.string(forKey: "emp_ID") {
print(UserInput)
} else {
// focus on the text field if it's empty
UserInput.becomeFirstResponder() }
UserInput.text = defaults.object(forKey: "emp_ID") as! String?
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
#IBAction func Switch(_ sender: UISwitch) {
if (sender.isOn == true) {
SaveIt = true
}
else{
SaveIt = false
}
}
#IBAction func Submit(_ sender: Any) {
if (SaveIt) {
let defaults = UserDefaults.standard
defaults.set(UserInput.text, forKey: "emp_ID")
defaults.synchronize()
}
let phone = "telprompt://1888247889pppp" + UserInput.text! + "p1p1p1p1";
let url = URL(string:phone)!
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else { UIApplication.shared.openURL(url)
}
}
}

How to disable front ViewController's view when RearViewController's view is active SWRevealViewController in Swift 3.0

How to disable user's interaction with front view controller - namely with class ViewController in my case, when the rear menu is shown. With the current code, when rear menu is shown, bookCleaningButton is not disabled.
import UIKit
class ViewController: UIViewController, SWRevealViewControllerDelegate {
#IBOutlet weak var menuButton: UIBarButtonItem!
#IBOutlet weak var bookCleaningButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.revealViewController().rearViewRevealWidth = self.view.frame.width - 80
//revela the menu if it is not nil
if self.revealViewController() != nil {
self.revealViewController().delegate = self
menuButton.target = self.revealViewController()
menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()
}
}
func revealController(revealController: SWRevealViewController!, willMoveToPosition position: FrontViewPosition) {
if revealController.frontViewPosition == FrontViewPosition.left {
self.view.isUserInteractionEnabled = false
}
else {
self.view.isUserInteractionEnabled = true
}
}
}
You should handle this in your Menu view controller rather. The reveal view controller has access to the frontViewController and that property can be used to set the userInteractionEnabled as false.
So, in your Menu View Controller write this this code in the viewWillAppear method:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.revealViewController().view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
self.revealViewController().frontViewController.revealViewController().tapGestureRecognizer()
self.revealViewController().frontViewController.view.isUserInteractionEnabled = false
}
And in the same Menu view Controller add the following code in the viewWillDisappear method:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.revealViewController().frontViewController.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
self.revealViewController().frontViewController.view.isUserInteractionEnabled = true
}
The above code also adds other gestures, but those can be optional. The main action happens at these two lines:
self.revealViewController().frontViewController.view.isUserInteractionEnabled = false
self.revealViewController().frontViewController.view.isUserInteractionEnabled = true
Hope this solves your issue. Cheers.
In your front view controller class. Write this code on the viewdidload() method.
override func viewDidLoad() {
super.viewDidLoad()
menuBtn.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), for: .touchUpInside)
revealViewController().delegate = self
// Once time - See documented SWRevealViewController.h
revealViewController().tapGestureRecognizer()
revealViewController().panGestureRecognizer()
}
and then use this delegate from the SWRevealviewcontroller in the frontviewcontroller
func revealController(_ revealController: SWRevealViewController!, willMoveTo position: FrontViewPosition) {
if position == FrontViewPosition.right {
revealController.frontViewController.view.isUserInteractionEnabled = false
}
else {
revealController.frontViewController.view.isUserInteractionEnabled = true
}
}
this will work up to your expectation....

IOS 10 - Swift 3.0: Stop the delegated function to save the image

I'm making an App with swift 3, xCode 8.2 and IOS10. The interface has a thermal vision screen (FLIR ONE). My question is, how can I take a photo? My code is:
import UIKit
class ThermalCameraVC: UIViewController, FLIROneSDKImageReceiverDelegate, FLIROneSDKStreamManagerDelegate {
//MARK: OUTLETS
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var labelStatusCamera: UITextField!
#IBOutlet weak var labelCargeCamera: UITextField!
#IBOutlet weak var icnCancelPicture: UIButton!
#IBOutlet weak var icnUploadPicture: UIButton!
#IBOutlet weak var iconTakePicture: UIButton!
//MARK: VARIABLES
var simulatorStatus = false
var cameraBussy = false
override func viewDidLoad() {
super.viewDidLoad()
FLIROneSDKStreamManager.sharedInstance().addDelegate(self)
FLIROneSDKStreamManager.sharedInstance().imageOptions = FLIROneSDKImageOptions(rawValue: FLIROneSDKImageOptions.blendedMSXRGBA8888Image.rawValue)!
icnCancelPicture.isHidden = true
icnUploadPicture.isHidden = true
}
//MARK: CANCEL PICTURE
#IBAction func cancelPicture(_ sender: Any) {
cameraBussy = false
}
//MARK: UPLOAD PICTURE AMAZON S3
#IBAction func uploadPicture(_ sender: Any) {
}
func flirOneSDKDelegateManager(_ delegateManager: FLIROneSDKDelegateManager!, didReceiveBlendedMSXRGBA8888Image msxImage: Data!, imageSize size: CGSize){
let image = FLIROneSDKUIImage(format: FLIROneSDKImageOptions.blendedMSXRGBA8888Image, andData: msxImage, andSize: size)
//HERE I NEED TO STOP THE DELEGATED FUNCTION TO SAVE THE IMAGE !!
if self.cameraBussy{
//cameraBussy = false
}else{
DispatchQueue.main.async{
self.imageView.image = image
}
}
}
#IBAction func takeThermalPicture(_ sender: Any) {
cameraBussy = true
icnCancelPicture.isHidden = false
icnUploadPicture.isHidden = false
iconTakePicture.isHidden = true
}
}
How can I stop the flow of data in this delegated function? Because it is continually calling.
Set the delegate value to nil.
#IBAction func takeThermalPicture(_ sender: Any) {
FLIROneSDKStreamManager.sharedInstance().addDelegate(nil)
cameraBussy = true
icnCancelPicture.isHidden = false
icnUploadPicture.isHidden = false
iconTakePicture.isHidden = true
}