I am having some problems with function textFieldShouldReturn as far at i understand it should be called when enter are pressed on the keyboard but it does not. I have tried to search for solution on google and here but have not found a answer that solved the problem because most of the answers here on the webpage i have fund are a 3 years or older and the solutions from those did not help much.
I am using it in a UIView where the delegates for the textField is set in the function awakeFromNib() and i have tried some other delegate function textViewDidChangeSelection that does work so i am at a lost why it is not working.
Here is how the xib file looks
Here is the code that i am using as a popup:
import UIKit
class CuePointPopup: UIView,UITextFieldDelegate,UITextViewDelegate
{
#IBOutlet var labelCueNumberInImage: UILabel!
#IBOutlet var labelCueNumber: UILabel!
#IBOutlet var labelLayerName: UILabel!
#IBOutlet var labelPageNumber: UILabel!
#IBOutlet weak var view: UIImageView!
#IBOutlet var textFieldWhoText: UITextField!
#IBOutlet var textViewWhatText: UITextView!
#IBOutlet var textFieldWhereText: UITextField!
#IBOutlet var textFieldPageNumber: UITextField!
#IBOutlet var textFieldCueText: UITextField!
#IBOutlet var boxArrowLeft: UIImageView!
#IBOutlet var boxArrowRight: UIImageView!
#IBOutlet var boxArrowLeftTopConstraint: NSLayoutConstraint!
#IBOutlet var boxArrowRightTopConstraint: NSLayoutConstraint!
var cuePointObj:CuePoint!
var blockBtnClickedSave:((CuePoint) -> ())!
var blockBtnClickedCancel:((CuePoint) -> ())!
var blockBtnClickedDelete:((CuePoint) -> ())!
var blockTextChangedForPageNumber:((String, CuePoint) -> ())!
#IBOutlet var btnOutletVisibleOnPage: UIButton!
var isVisible = false
class func loadNib() -> CuePointPopup
{
return Bundle.main.loadNibNamed("CuePointPopup", owner: self,options: nil)!.last as! CuePointPopup
}
override func awakeFromNib() {
self.textFieldWhoText.delegate = self
self.textViewWhatText.delegate = self
self.textFieldWhereText.delegate = self
self.textFieldCueText.delegate = self
textViewWhatText.text = "Hello"
}
func setViewData(cueModel:CuePoint) {
self.cuePointObj = cueModel
labelCueNumberInImage.text = cueModel.cueNumber
labelCueNumber.text = "Cue #:" + cueModel.cueNumber
labelLayerName.text = "Layer #:" + cueModel.layerName
labelPageNumber.text = "Page #:" + cueModel.pageNumber
textFieldPageNumber.text = cueModel.pageNumber
textFieldWhoText.text = cueModel.whoString
textViewWhatText.text = cueModel.whatString
textFieldWhereText.text = cueModel.whereString
textFieldCueText.text = cueModel.cueTextString
if cueModel.isVisibleOnPage == true {
btnOutletVisibleOnPage.setImage(UIImage(named: "SelectedBox"), for: [])
btnOutletVisibleOnPage.tag = 1
}else{
btnOutletVisibleOnPage.setImage(UIImage(named: "UnselectedBox"), for: [])
btnOutletVisibleOnPage.tag = 0
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.text != "" {
if blockTextChangedForPageNumber != nil {
self.blockTextChangedForPageNumber(textField.text!, self.cuePointObj)
}
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
//self.view.endEditing(true)
if self.textFieldWhoText.isEditing {
self.textFieldWhoText.endEditing(true)
} else if self.textFieldCueText.isEditing{
self.textFieldCueText.endEditing(true)
} else if self.textFieldWhereText.isEditing {
self.textFieldWhereText.endEditing(true)
} else {
self.textViewWhatText.endEditing(true)
}
//self.view.endEditing(true)
return false
}
}
Here is how i load the XIB
#IBOutlet weak var bookView: UIView!
var objCuePopup:CuePointPopup!
if objCuePopup != nil {
objCuePopup.removeFromSuperview()
}
objCuePopup = CuePointPopup.loadNib()
objCuePopup = CuePointPopup.loadNib()
objCuePopup.frame = CGRect(x:cuePointModal.cueX, y:0, width:465, height:410)
objCuePopup.center = CGPoint(x:objCuePopup.center.x, y:cuePointModal.cueY + 5)
//Set Y value for Popup View
if objCuePopup.frame.origin.y < bookView.frame.origin.y {
objCuePopup.frame.origin.y = bookView.frame.origin.y
}
let popupMaxY = objCuePopup.frame.maxY
let bookViewMaxY = bookView.frame.maxY
if popupMaxY > bookViewMaxY {
objCuePopup.frame.origin.y = bookViewMaxY - objCuePopup.frame.size.height
}
//Set X value for Popup View
if cuePointModal.cueX > 455 {
objCuePopup.frame.origin.x = cuePointModal.cueX - 455
objCuePopup.boxArrowLeft.isHidden = true
objCuePopup.boxArrowRight.isHidden = false
let rightY = cuePointModal.cueY - objCuePopup.frame.origin.y
objCuePopup.boxArrowRightTopConstraint.constant = rightY + 3
}else{
objCuePopup.frame.origin.x = cuePointModal.cueX + 40
objCuePopup.boxArrowLeft.isHidden = false
objCuePopup.boxArrowRight.isHidden = true
let leftY = cuePointModal.cueY - objCuePopup.frame.origin.y
objCuePopup.boxArrowLeftTopConstraint.constant = leftY + 3
}
objCuePopup.setViewData(cueModel: cuePointModal)
objCuePopup.textFieldWhoText.delegate = self
objCuePopup.textFieldWhereText.delegate = self
objCuePopup.textViewWhatText.delegate = self
objCuePopup.textFieldCueText.delegate = self
bookView.addSubview(objCuePopup)
I hope that someone here can help me with this problem.
Related
This question already has answers here:
How to initialize properties that depend on each other
(4 answers)
Closed 2 years ago.
Trying to make a simple Blackjack app to get comfortable with using Xcode. I've never coded in Swift before and have a little experience in C++. Having an error I don't know how to fix. I'm having trouble applying other answers to similar questions to my situation.
I'm not totally sure what's causing the problem, let alone how to fix it :)
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
var balance = 500
let suits = ["h","d","c","s"]
//user card declarations
#IBOutlet weak var userCard1: UIImageView!
#IBOutlet weak var userCard2: UIImageView!
#IBOutlet weak var userCard3: UIImageView!
#IBOutlet weak var userCard4: UIImageView!
#IBOutlet weak var userCard5: UIImageView!
#IBOutlet weak var userCard6: UIImageView!
#IBOutlet weak var userCard7: UIImageView!
#IBOutlet weak var userCard8: UIImageView!
#IBOutlet weak var userCard9: UIImageView!
#IBOutlet weak var userCard10: UIImageView!
//dealer card declarations
#IBOutlet weak var dealerCard1: UIImageView!
#IBOutlet weak var dealerCard2: UIImageView!
#IBOutlet weak var dealerCard3: UIImageView!
#IBOutlet weak var dealerCard4: UIImageView!
#IBOutlet weak var dealerCard5: UIImageView!
var win = false
var bet = 0
//bet label
#IBOutlet weak var betLabel: UILabel!
//bet slider
#IBAction func betSlider(_ sender: UISlider) {
betLabel.text = String(Int(sender.value))
}
#IBOutlet weak var betSliderValue: UISlider!
var userCardSlot = 3
var dealerCardSlot = 3
var userTotal = 0
var dealerTotal = 0
//user cards displayed
var userCardArray = [userCard1, userCard2, userCard3, userCard4, userCard5, userCard6, userCard7, userCard8, userCard9, userCard10]
//dealer cards displayed
var dealerCardArray = [dealerCard1, dealerCard2, dealerCard3, dealerCard4, dealerCard5]
//hit button
#IBAction func hitTapped(_ sender: Any) {
var cardNum = Int.random(in: 2...14)
var cardSuit = Int(arc4random()) % 4
userCardArray[userCardSlot].image = UIImage(named: "\(cardSuit)card\(cardNum)")
}
//stand button
#IBAction func standTapped(_ sender: Any) {
for userTotal in userCardArray.reversed() {
userTotal += cardNum
}
for dealerTotal in dealerCardArray {
dealerTotal += cardNum
}
while dealerTotal < 17 {
dealerCardSlot += 1
dealerCardArray[dealerCardSlot].image = UIImage(named: "\(cardSuit)card\(cardNum)")
}
if dealerTotal <= userTotal {
win = true
} else {
win = false
}
}
#IBAction func newRoundTapped(_ sender: Any) {
bet = Int(betSliderValue.value)
userCardArray[0].image = UIImage(named: "\(cardSuit)card\(cardNum)")
userCardArray[1].image = UIImage(named: "\(cardSuit)card\(cardNum)")
dealerCardArray[0].image = UIImage(named: "\(cardSuit)card\(cardNum)")
dealerCardArray[0].image = UIImage(named: "Red_back.jpg")
//prompt for hit or stand
if win == true {
balance += (bet * 2)
} else {
balance -= bet
}
}
}
Any help's appreciated!
You generally cannot use one property to initialize another outside of init, because when you do:
var b = a + 1
the compiler implicitly does:
var b = self.a + 1
but self is not yet available; it's only available during the init.
The only exception is a lazy property initializer:
lazy var b: Int = self.a + 1
In your case, you can move the initialization into init:
var userCardArray: [UIImageView]
init() {
self.userCardArray = [userCard1, userCard2, ... ]
}
Hi I'm a new swift developer and I'm trying to find a way to load all of my textfields in the background thread then make it go back to the mainthread before a viewcontroller appear.
Because in my viewcontroller I have like almost 20 textfield that need to setup like its style, placeholders and etc.. So it takes quite a while for the viewcontroller to appear when I tapped on the button that handle segue to that vc.
I know that I can use this to do the setup textfields in the background
DispatchQueue.global(qos: .userInteractive).async {
<#code#>
}
however I dont know where to put this code. I tried to put it in the viewDidLoad but that doesnt seem to work.
EDIT: ADD IN MY CODE
import UIKit
import MaterialComponents.MaterialTextFields
class AddNewDataVC: UIViewController {
//Outlet
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var saveNewDataBtn: UIButton!
#IBOutlet weak var sowInfoInputsStackView: UIStackView!
#IBOutlet weak var giltInfoInputsStackView: UIStackView!
#IBOutlet weak var matingInfoInputsStackView: UIStackView!
#IBOutlet weak var farrowInfoInputsStackView: UIStackView!
#IBOutlet weak var vaccinTable: UITableView!
#IBOutlet weak var pigTypeTextField: PickerTextField!
#IBOutlet weak var genderTextField: PickerTextField!
#IBOutlet weak var chipIDTextField: MDCTextField!
#IBOutlet weak var breedTextField: MDCTextField!
#IBOutlet weak var subBreedTextField: MDCTextField!
#IBOutlet weak var dadIDTextField: MDCTextField!
#IBOutlet weak var momIDTextField: MDCTextField!
#IBOutlet weak var penIDTextField: MDCTextField!
#IBOutlet weak var weightTextField: MDCTextField!
#IBOutlet weak var parityTextField: MDCTextField!
#IBOutlet weak var birthDateTextField: PickerTextField!
#IBOutlet weak var weanDateTextField: PickerTextField!
#IBOutlet weak var arrivalDateTextField: PickerTextField!
#IBOutlet weak var herdEntryDateTextField: PickerTextField!
#IBOutlet weak var startOffDutySowDateTextField: PickerTextField!
#IBOutlet weak var semenFromBoarIDTextField: MDCTextField!
#IBOutlet weak var technicianNameTextField: PickerTextField!
#IBOutlet weak var matingDateTextField: PickerTextField!
#IBOutlet weak var estimateBirthDateTextField: PickerTextField!
#IBOutlet weak var realBirthDateTextField: PickerTextField!
#IBOutlet weak var totalNumberOfNewBornsTextField: MDCTextField!
#IBOutlet weak var totalNumberOfDeadNewBornsTextField: MDCTextField!
#IBOutlet weak var averageWeightOfNewBornsTextField: MDCTextField!
#IBOutlet weak var accoucheurNameTextField: MDCTextField!
#IBOutlet weak var newBornDeathReason1TextField: MDCTextField!
#IBOutlet weak var newBornDeathReason2TextField: MDCTextField!
#IBOutlet weak var newBornDeathReason3TextField: MDCTextField!
#IBOutlet weak var newBornCullReason1TextField: MDCTextField!
#IBOutlet weak var newBornCullReason2TextField: MDCTextField!
#IBOutlet weak var newBornCullReason3TextField: MDCTextField!
//Properties
var pigTypeController: MDCTextInputControllerUnderline?
var genderController: MDCTextInputControllerUnderline?
var chipIDController: MDCTextInputControllerUnderline?
var breedController: MDCTextInputControllerUnderline?
var subBreedController: MDCTextInputControllerUnderline?
var dadIDController: MDCTextInputControllerUnderline?
var momIDController: MDCTextInputControllerUnderline?
var penIDController: MDCTextInputControllerUnderline?
var weightController: MDCTextInputControllerUnderline?
var parityController: MDCTextInputControllerUnderline?
var birthDateController: MDCTextInputControllerUnderline?
var weanDateController: MDCTextInputControllerUnderline?
var arrivalDateController: MDCTextInputControllerUnderline?
var herdEntryDateController: MDCTextInputControllerUnderline?
var startOffDutySowDateController: MDCTextInputControllerUnderline?
var semenFromBoarIDController: MDCTextInputControllerUnderline?
var techicianNameController: MDCTextInputControllerUnderline?
var matingDateController: MDCTextInputControllerUnderline?
var estimateBirthDateController: MDCTextInputControllerUnderline?
var realBirthDateController: MDCTextInputControllerUnderline?
var totalNumberOfNewBornsController: MDCTextInputControllerUnderline?
var totalNumberOfDeadNewBornsController: MDCTextInputControllerUnderline?
var averageWeightOfNewBornsController: MDCTextInputControllerUnderline?
var accoucheurNameController: MDCTextInputControllerUnderline?
var newBornDeathReason1Controller: MDCTextInputControllerUnderline?
var newBornDeathReason2Controller: MDCTextInputControllerUnderline?
var newBornDeathReason3Controller: MDCTextInputControllerUnderline?
var newBornCullReason1Controller: MDCTextInputControllerUnderline?
var newBornCullReason2Controller: MDCTextInputControllerUnderline?
var newBornCullReason3Controller: MDCTextInputControllerUnderline?
var allTextFieldControllers = [MDCTextInputControllerUnderline]()
var injectedVaccinArray = [[String : Any]]()
override func viewDidLoad() {
super.viewDidLoad()
setupTextFields()
registerKeyboardNotifications()
addGestureRecognizer()
vaccinTable.dataSource = self
vaccinTable.delegate = self
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
#IBAction func closeAddNewDataPopupBtnPressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
#IBAction func saveNewDataBtnPressed(_ sender: Any) {
}
#IBAction func addVaccinDataBtnPressed(_ sender: UIButton) {
let getDestStoryboard = UIStoryboard(name: "AddNewData", bundle: nil)
let popupVC = getDestStoryboard.instantiateViewController(withIdentifier: "addVaccinDataVC") as! AddVaccinInfoVC
popupVC.popupDelegate = self
self.present(popupVC, animated: true, completion: nil)
}
}
extension AddNewDataVC {
func setupTextFields() {
pigTypeController = MDCTextInputControllerUnderline(textInput: pigTypeTextField)
pigTypeTextField.delegate = self
pigTypeTextField.addData(data: PIG_TYPES_ENUM.allValues)
pigTypeController?.placeholderText = "Loại lợn"
allTextFieldControllers.append(pigTypeController!)
genderController = MDCTextInputControllerUnderline(textInput: genderTextField)
genderTextField.delegate = self
genderTextField.addData(data: GENDERS)
genderController?.placeholderText = "Giới tính"
allTextFieldControllers.append(genderController!)
chipIDController = MDCTextInputControllerUnderline(textInput: chipIDTextField)
chipIDTextField.delegate = self
chipIDController?.placeholderText = "Số chip"
allTextFieldControllers.append(chipIDController!)
breedController = MDCTextInputControllerUnderline(textInput: breedTextField)
breedTextField.delegate = self
breedController?.placeholderText = "Giống"
allTextFieldControllers.append(breedController!)
subBreedController = MDCTextInputControllerUnderline(textInput: subBreedTextField)
subBreedTextField.delegate = self
subBreedController?.placeholderText = "Giống phụ"
allTextFieldControllers.append(subBreedController!)
dadIDController = MDCTextInputControllerUnderline(textInput: dadIDTextField)
dadIDTextField.delegate = self
dadIDController?.placeholderText = "Số chip bố mẹ"
allTextFieldControllers.append(dadIDController!)
momIDController = MDCTextInputControllerUnderline(textInput: momIDTextField)
momIDTextField.delegate = self
momIDController?.placeholderText = "Số chip mẹ"
allTextFieldControllers.append(momIDController!)
penIDController = MDCTextInputControllerUnderline(textInput: penIDTextField)
penIDTextField.delegate = self
penIDController?.placeholderText = "Số chuồng"
allTextFieldControllers.append(penIDController!)
weightController = MDCTextInputControllerUnderline(textInput: weightTextField)
weightTextField.delegate = self
weightController?.placeholderText = "Số kg"
allTextFieldControllers.append(weightController!)
parityController = MDCTextInputControllerUnderline(textInput: parityTextField)
parityTextField.delegate = self
parityController?.placeholderText = "Số lứa"
allTextFieldControllers.append(parityController!)
birthDateController = MDCTextInputControllerUnderline(textInput: birthDateTextField)
birthDateTextField.delegate = self
birthDateController?.placeholderText = "Ngày sinh"
allTextFieldControllers.append(birthDateController!)
weanDateController = MDCTextInputControllerUnderline(textInput: weanDateTextField)
weanDateTextField.delegate = self
weanDateController?.placeholderText = "Ngày cai sữa"
allTextFieldControllers.append(weanDateController!)
arrivalDateController = MDCTextInputControllerUnderline(textInput: arrivalDateTextField)
arrivalDateTextField.delegate = self
arrivalDateController?.placeholderText = "Ngày đến"
allTextFieldControllers.append(arrivalDateController!)
herdEntryDateController = MDCTextInputControllerUnderline(textInput: herdEntryDateTextField)
herdEntryDateTextField.delegate = self
herdEntryDateController?.placeholderText = "Ngày nhập đàn"
allTextFieldControllers.append(herdEntryDateController!)
startOffDutySowDateController = MDCTextInputControllerUnderline(textInput: startOffDutySowDateTextField)
startOffDutySowDateTextField.delegate = self
startOffDutySowDateController?.placeholderText = "Ngày nái nghỉ"
allTextFieldControllers.append(startOffDutySowDateController!)
semenFromBoarIDController = MDCTextInputControllerUnderline(textInput: semenFromBoarIDTextField)
semenFromBoarIDTextField.delegate = self
semenFromBoarIDController?.placeholderText = "Mã heo nọc"
allTextFieldControllers.append(semenFromBoarIDController!)
techicianNameController = MDCTextInputControllerUnderline(textInput: technicianNameTextField)
technicianNameTextField.delegate = self
techicianNameController?.placeholderText = "Người phối"
technicianNameTextField.addData(data: TECHNICIAN_NAMES)
allTextFieldControllers.append(techicianNameController!)
matingDateController = MDCTextInputControllerUnderline(textInput: matingDateTextField)
matingDateTextField.delegate = self
matingDateController?.placeholderText = "Ngày phối"
allTextFieldControllers.append(matingDateController!)
estimateBirthDateController = MDCTextInputControllerUnderline(textInput: estimateBirthDateTextField)
estimateBirthDateTextField.delegate = self
estimateBirthDateController?.placeholderText = "Ngày đẻ dự kiến"
allTextFieldControllers.append(estimateBirthDateController!)
realBirthDateController = MDCTextInputControllerUnderline(textInput: realBirthDateTextField)
realBirthDateTextField.delegate = self
realBirthDateController?.placeholderText = "Ngày đẻ thực tế"
allTextFieldControllers.append(realBirthDateController!)
totalNumberOfNewBornsController = MDCTextInputControllerUnderline(textInput: totalNumberOfNewBornsTextField)
totalNumberOfNewBornsTextField.delegate = self
totalNumberOfNewBornsController?.placeholderText = "Tổng heo con sinh"
allTextFieldControllers.append(totalNumberOfNewBornsController!)
totalNumberOfDeadNewBornsController = MDCTextInputControllerUnderline(textInput: totalNumberOfDeadNewBornsTextField)
totalNumberOfDeadNewBornsTextField.delegate = self
totalNumberOfDeadNewBornsController?.placeholderText = "Tổng heo con chết"
allTextFieldControllers.append(totalNumberOfDeadNewBornsController!)
averageWeightOfNewBornsController = MDCTextInputControllerUnderline(textInput: averageWeightOfNewBornsTextField)
averageWeightOfNewBornsTextField.delegate = self
averageWeightOfNewBornsController?.placeholderText = "Kg trung bình"
allTextFieldControllers.append(averageWeightOfNewBornsController!)
accoucheurNameController = MDCTextInputControllerUnderline(textInput: accoucheurNameTextField)
accoucheurNameTextField.delegate = self
accoucheurNameController?.placeholderText = "Người đỡ đẻ"
allTextFieldControllers.append(accoucheurNameController!)
newBornDeathReason1Controller = MDCTextInputControllerUnderline(textInput: newBornDeathReason1TextField)
newBornDeathReason1TextField.delegate = self
newBornDeathReason1Controller?.placeholderText = "Chết khô"
allTextFieldControllers.append(newBornDeathReason1Controller!)
newBornDeathReason2Controller = MDCTextInputControllerUnderline(textInput: newBornDeathReason2TextField)
newBornDeathReason2TextField.delegate = self
newBornDeathReason2Controller?.placeholderText = "Chết lưu"
allTextFieldControllers.append(newBornDeathReason2Controller!)
newBornDeathReason3Controller = MDCTextInputControllerUnderline(textInput: newBornDeathReason3TextField)
newBornDeathReason3TextField.delegate = self
newBornDeathReason3Controller?.placeholderText = "Chết tươi"
allTextFieldControllers.append(newBornDeathReason3Controller!)
newBornCullReason1Controller = MDCTextInputControllerUnderline(textInput: newBornCullReason1TextField)
newBornCullReason1TextField.delegate = self
newBornCullReason1Controller?.placeholderText = "Loại nhỏ"
allTextFieldControllers.append(newBornCullReason1Controller!)
newBornCullReason2Controller = MDCTextInputControllerUnderline(textInput: newBornCullReason2TextField)
newBornCullReason2TextField.delegate = self
newBornCullReason2Controller?.placeholderText = "Loại yếu"
allTextFieldControllers.append(newBornCullReason2Controller!)
newBornCullReason3Controller = MDCTextInputControllerUnderline(textInput: newBornCullReason3TextField)
newBornCullReason3TextField.delegate = self
newBornCullReason3Controller?.placeholderText = "Loại nhỏ"
allTextFieldControllers.append(newBornCullReason3Controller!)
for controller in allTextFieldControllers {
controller.activeColor = Theme.darkAccent
controller.floatingPlaceholderActiveColor = Theme.darkAccent
}
}
func addGestureRecognizer() {
let tapRecognizer = UITapGestureRecognizer(target: self,
action: #selector(tapDidTouch(sender: )))
self.scrollView.addGestureRecognizer(tapRecognizer)
}
#objc func tapDidTouch(sender: Any) {
self.view.endEditing(true)
}
func registerKeyboardNotifications() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(
self,
selector: #selector(keyboardWillShow(notif:)),
name: .UIKeyboardWillChangeFrame,
object: nil)
notificationCenter.addObserver(
self,
selector: #selector(keyboardWillShow(notif:)),
name: .UIKeyboardWillShow,
object: nil)
notificationCenter.addObserver(
self,
selector: #selector(keyboardWillHide(notif:)),
name: .UIKeyboardWillHide,
object: nil)
}
#objc func keyboardWillShow(notif: Notification) {
guard let frame = notif.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else {
return
}
scrollView.contentInset = UIEdgeInsets(top: 0.0,
left: 0.0,
bottom: frame.height,
right: 0.0)
}
#objc func keyboardWillHide(notif: Notification) {
scrollView.contentInset = UIEdgeInsets()
}
func toggleFarrowInfoInputsStackView(toggle: Bool) {
if toggle {
sowInfoInputsStackView.isHidden = false
} else {
sowInfoInputsStackView.isHidden = true
}
}
func toggleGiltInputs(toggle: Bool) {
if toggle {
giltInfoInputsStackView.isHidden = false
} else {
giltInfoInputsStackView.isHidden = true
}
}
func toggleOffDutySowInputs(toggle: Bool) {
if toggle {
startOffDutySowDateTextField.isHidden = false
} else {
startOffDutySowDateTextField.isHidden = true
}
}
func toggleMatingInputs(toggle: Bool) {
if toggle {
matingInfoInputsStackView.isHidden = false
} else {
matingInfoInputsStackView.isHidden = true
}
}
func toggleFarrowInputs(toggle: Bool) {
if toggle {
farrowInfoInputsStackView.isHidden = false
} else {
farrowInfoInputsStackView.isHidden = true
}
}
func toggleParityTextField(toggle: Bool) {
if toggle {
parityTextField.isHidden = false
} else {
parityTextField.isHidden = true
}
}
}
extension AddNewDataVC: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
func textFieldDidEndEditing(_ textField: UITextField) {
if let textField = textField as? PickerTextField {
let text = textField.text?.lowercased()
if !textField.isDatePicker && textField == pigTypeTextField {
if text!.contains("nái") || textField.text! == PIG_TYPES_ENUM.gilt.rawValue {
toggleFarrowInfoInputsStackView(toggle: true)
if textField.text! == PIG_TYPES_ENUM.gilt.rawValue {
toggleGiltInputs(toggle: true)
toggleOffDutySowInputs(toggle: false)
toggleMatingInputs(toggle: false)
toggleFarrowInputs(toggle: false)
} else if textField.text! == PIG_TYPES_ENUM.offDutySow.rawValue {
toggleGiltInputs(toggle: true)
toggleOffDutySowInputs(toggle: true)
toggleMatingInputs(toggle: false)
toggleFarrowInputs(toggle: false)
} else if textField.text! == PIG_TYPES_ENUM.matingSow.rawValue {
toggleGiltInputs(toggle: true)
toggleOffDutySowInputs(toggle: false)
toggleMatingInputs(toggle: true)
toggleFarrowInputs(toggle: false)
} else if textField.text! == PIG_TYPES_ENUM.farrow.rawValue {
toggleGiltInputs(toggle: true)
toggleOffDutySowInputs(toggle: false)
toggleMatingInputs(toggle: true)
toggleFarrowInputs(toggle: true)
}
} else {
toggleFarrowInfoInputsStackView(toggle: false)
toggleGiltInputs(toggle: false)
toggleOffDutySowInputs(toggle: false)
toggleMatingInputs(toggle: false)
toggleFarrowInputs(toggle: false)
if textField.text! == PIG_TYPES_ENUM.boar.rawValue {
genderTextField.text = "Đực"
genderTextField.isUserInteractionEnabled = false
} else {
genderTextField.text = ""
genderTextField.isUserInteractionEnabled = true
}
}
} else if !textField.isDatePicker && textField == genderTextField {
if textField.text == "Cái" {
toggleParityTextField(toggle: true)
} else {
toggleParityTextField(toggle: false)
}
}
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField is PickerTextField {
textField.resignFirstResponder()
return false
} else {
return true
}
}
}
extension AddNewDataVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return injectedVaccinArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = vaccinTable.dequeueReusableCell(withIdentifier: "injectedVaccinCell", for: indexPath) as? InjectedVaccinCell else {
return UITableViewCell()
}
cell.configureCell(value: injectedVaccinArray[indexPath.row])
return cell
}
}
extension AddNewDataVC: PopupDelegates {
func popupValueSelected(value: [String : Any]) {
self.injectedVaccinArray.append(value)
self.vaccinTable.reloadData()
}
}
There are alot of room for improvement I know but I'm just learned swift so sorry if my code make you itch haha. right now I'm just focusing on make it works and will try to clean it up later down the road.
i am doing a form using textfield and textview
after i key in all the information and click the submit button, the app will close and jump to my viewcontroller.swift and show like the below photo
and this is my viewcontroller.swift
import UIKit
import MessageUI
class ContactViewController:UIViewController,MFMailComposeViewControllerDelegate,UITextViewDelegate,UITextFieldDelegate {
#IBOutlet weak var message: UITextView!
#IBOutlet weak var contactSubject: UITextField!
#IBOutlet weak var contactNumber: UITextField!
#IBOutlet weak var contactEmail: UITextField!
#IBOutlet weak var contactName: UITextField!
#IBOutlet weak var contactDes: UILabel!
#IBOutlet weak var contactTitle: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
contactTitle.text = "SEND US A MESSAGES"
contactTitle.sizeToFit()
contactDes.text = "Do you have anything in your mind to tell us?\nPlease don’t hesitate to get in touch to us via our contact form."
contactDes.sizeToFit()
//Contact Form
contactName.delegate = self
contactEmail.delegate = self
contactNumber.delegate = self
contactSubject.delegate = self
message.delegate = self
self.message.isUserInteractionEnabled = true
self.message.isEditable = true
let borderColor : UIColor = UIColor.init(red: 46.0/255.0, green: 49.0/255.0, blue: 146.0/255.0, alpha: 1)
contactName.layer.borderWidth = 1
contactName.layer.borderColor = borderColor.cgColor
contactEmail.layer.borderWidth = 1
contactEmail.layer.borderColor = borderColor.cgColor
contactSubject.layer.borderWidth = 1
contactSubject.layer.borderColor = borderColor.cgColor
contactNumber.layer.borderWidth = 1
contactNumber.layer.borderColor = borderColor.cgColor
message.layer.borderWidth = 1
message.layer.borderColor = borderColor.cgColor
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
contactName.resignFirstResponder()
contactEmail.resignFirstResponder()
contactNumber.resignFirstResponder()
contactSubject.resignFirstResponder()
return true
}
#IBAction func submitbtn(_ sender: Any) {
let mailVC = MFMailComposeViewController()
mailVC.mailComposeDelegate = self
mailVC.setSubject(contactSubject.text!)
let email = contactEmail.text!.lowercased()
let finalemail = email.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
let mailcontent = "Name :\(contactName.text!)\n\n Email:\(finalemail)\n\n Contact Numer :\(contactNumber.text!)\n\n Subject :\(contactSubject.text!)\n\n Message :\(message.text!)"
mailVC.setMessageBody(mailcontent, isHTML: false)
let toRecipent = "abc#example.com"
mailVC.setToRecipients([toRecipent])
self.present(mailVC, animated: true, completion: nil)
}
}
I am making a calculator app in iOS 9, Swift and with Xcode 7 and I would like to know how to create UIButtons when the user switches to landscape mode only. Adding more operators to the left of the number and AC Button and changing the constraints, shifting the buttons over to make room for the new ones. The basic calculator for iOS does this and I'm wondering how??
I'm new to iOS development and I have been web browsing to only find an overriding function called: viewWillTransitionToSize(). Is this the right function to do this sort of thing?
Also, everytime I enter the landscape view, another button gets created. How can I stop this from happening?
Attached is my programmatic creation of the UIbutton and the function I listed above.
Sorry for the array of questions/problems. I am having difficulties finding tutorials or help on this issue. Any guidance or solution will be helpful. Thank you so much.
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var outputDisplay: UILabel!
#IBOutlet weak var number7: UIButton!
#IBOutlet weak var number1: UIButton!
#IBOutlet weak var number2: UIButton!
#IBOutlet weak var number3: UIButton!
#IBOutlet weak var number4: UIButton!
#IBOutlet weak var number5: UIButton!
#IBOutlet weak var number6: UIButton!
#IBOutlet weak var number9: UIButton!
#IBOutlet weak var number8: UIButton!
#IBOutlet weak var numberZero: UIButton!
#IBOutlet weak var decimalPoint: UIButton!
#IBOutlet weak var plusMinusToggle: UIButton!
#IBOutlet weak var acClear: UIButton!
#IBOutlet weak var equalButton: UIButton!
#IBOutlet weak var multiply: UIButton!
#IBOutlet weak var divide: UIButton!
#IBOutlet weak var subtraction: UIButton!
#IBOutlet weak var addition: UIButton!
#IBOutlet weak var deletion: UIButton!
#IBOutlet weak var squareRoot: UIButton!
var typing:Bool = false
var firstNumber: Float = 0.0
var secondNumber: Float = 0.0
var operation:String = ""
var result: Float = 0.0
var valueToPass: Float = 0.0
override func viewDidLoad() {
super.viewDidLoad()
number1.layer.cornerRadius = number1.bounds.size.width / 8.0
number2.layer.cornerRadius = number2.bounds.size.width / 8.0
number3.layer.cornerRadius = number3.bounds.size.width / 8.0
number4.layer.cornerRadius = number4.bounds.size.width / 8.0
number5.layer.cornerRadius = number5.bounds.size.width / 8.0
number6.layer.cornerRadius = number6.bounds.size.width / 8.0
number7.layer.cornerRadius = number7.bounds.size.width / 8.0
number8.layer.cornerRadius = number8.bounds.size.width / 8.0
number9.layer.cornerRadius = number9.bounds.size.width / 8.0
numberZero.layer.cornerRadius = numberZero.bounds.size.width / 8.0
equalButton.layer.cornerRadius = equalButton.bounds.size.width / 8.0
deletion.layer.cornerRadius = deletion.bounds.size.width / 8.0
plusMinusToggle.layer.cornerRadius = plusMinusToggle.bounds.size.width / 8.0
decimalPoint.layer.cornerRadius = decimalPoint.bounds.size.width / 8.0
acClear.layer.cornerRadius = acClear.bounds.size.width / 8.0
addition.layer.cornerRadius = addition.bounds.size.width / 8.0
divide.layer.cornerRadius = divide.bounds.size.width / 8.0
multiply.layer.cornerRadius = multiply.bounds.size.width / 8.0
subtraction.layer.cornerRadius = subtraction.bounds.size.width / 8.0
squareRoot.layer.cornerRadius = squareRoot.bounds.size.width / 8.0
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
if (UIDevice.currentDevice().orientation.isLandscape) {
print("Device in Lanscape")
let newButton1 = UIButton(type: UIButtonType.System) as UIButton
newButton1.frame = CGRectMake(100, 100, 100, 50)
newButton1.backgroundColor = UIColor.whiteColor()
newButton1.center = CGPoint(x: number1.frame.width, y: number1.frame.height)
newButton1.layer.cornerRadius = newButton1.bounds.size.width / 8.0
self.view.addSubview(newButton1)
}
else{}
}
#IBAction func numberPressed(sender: AnyObject) {
// set the variable "number" to whichever number the user presses
let number = sender.currentTitle!
if typing {
outputDisplay.text = outputDisplay.text! + String(number!)
} else {
outputDisplay.text = number!
}
typing = true
}
#IBAction func calculationPressed(sender: AnyObject) {
typing = false
firstNumber = Float(outputDisplay.text!)!
operation = sender.currentTitle!!
}
#IBAction func equalPressed(sender: AnyObject) {
secondNumber = Float(outputDisplay.text!)!
typing = false
//arithmetic operations
if operation == "+" {
result = firstNumber + secondNumber
}
else if operation == "-" {
result = firstNumber - secondNumber
}
else if operation == "✕" {
result = firstNumber * secondNumber
}
else if operation == "÷" {
result = firstNumber / secondNumber
}
// else if operation == "%" {
// result = (firstNumber * secondNumber) / 100
// }
else if operation == "√" {
result = sqrt(firstNumber)
}
outputDisplay.text = "\(result)"
}
#IBAction func squareRoot(sender: AnyObject) {
result = sqrt(Float(outputDisplay.text!)!)
outputDisplay.text = "\(result)"
}
#IBAction func deletePressed(sender: AnyObject) {
if outputDisplay.text!.characters.count != 0 {
outputDisplay.text = outputDisplay.text!.substringToIndex(outputDisplay.text!.endIndex.predecessor())
}
else{
outputDisplay.text = "0"
}
}
#IBAction func plusMinus(sender: AnyObject) {
if( outputDisplay.text![outputDisplay.text!.startIndex] == "-"){
outputDisplay.text!.removeAtIndex(outputDisplay.text!.startIndex)
}else{
outputDisplay.text!.insert("-", atIndex: outputDisplay.text!.startIndex)
}
}
#IBAction func decimal(sender: AnyObject) {
let decimal = sender.currentTitle!
outputDisplay.text = outputDisplay.text! + decimal!
}
#IBAction func clear(sender: AnyObject) {
result = 0
firstNumber = 0
secondNumber = 0
outputDisplay.text = "0"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I would do this using Size Classes. You can design different layouts and button arrangements in storyboard using the different size classes. If this application is on the iPhone, you would use Compact width and Regular height when in Portrait and Compact height and Regular width when in Landscape.
I have 3 textfields. I'm trying to make it have a Next button to go to from 1st to 2nd, and 2nd to 3rd, and a Done button once finished with the 3rd.
This is my code:
import Foundation
import UIKit
import Darwin
class View3on3 : UIViewController, UITextFieldDelegate {
#IBOutlet weak var APTeams: UITextField!
#IBOutlet weak var APRounds: UITextField!
#IBOutlet weak var APBreakers: UITextField!
#IBOutlet weak var ToAPBreak: UIButton!
override func viewDidLoad()
{
super.viewDidLoad()
initializeTextFields()
APTeams.delegate = self
APRounds.delegate = self
APBreakers.delegate = self
ToAPBreak.backgroundColor = UIColor.clearColor()
ToAPBreak.layer.cornerRadius = 11
ToAPBreak.layer.borderWidth = 1
ToAPBreak.layer.borderColor = self.view.tintColor.CGColor
}
func initializeTextFields()
{
APTeams.keyboardType = UIKeyboardType.NumberPad
APRounds.keyboardType = UIKeyboardType.NumberPad
APBreakers.keyboardType = UIKeyboardType.NumberPad
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if (textField == APTeams){
APRounds.becomeFirstResponder()
} else if (textField == APRounds){
APBreakers.becomeFirstResponder()
} else if (textField == APBreakers){
APBreakers.resignFirstResponder()
} else {
//etc//
}
return true
}
This isn't working at all. What do I have to do?
For NumberPad type keyboard types iOS not able to display the return key.So you may try like this.
func initializeTextFields()
{
APTeams.keyboardType = UIKeyboardType.NumbersAndPunctuation
APRounds.keyboardType = UIKeyboardType.NumbersAndPunctuation
APBreakers.keyboardType = UIKeyboardType.NumbersAndPunctuation
APTeams.returnKeyType = UIReturnKeyType.Next
APRounds.returnKeyType = UIReturnKeyType.Next
APBreakers.returnKeyType = UIReturnKeyType.Done
}