Hi
I am trying to learn Swift/iOS using @hollance’s cool book and my app deviates from the book, but takes many of the lessons learned. I am trying to refactor this code, I don’t expect someone to rewrite this for me, but it would be great to have some ideas. I’m still getting used to the swift/iOS environment and don’t know much of the SDK as I’m coming from other languages. Here is two functions that I would feel could be improved/shortened
The first function I have is a series of user text fields where I’m using a UIPicker, this just drops the picker when done is touched.
The second is me adding a uipicker and custom toolbar to each of the outlets along with a target that is used later on in the code to confirm that user has filled in all the necessary fields.
// drops the uipickerview when called
func donePicker(sender: UITextField){
if sportTextField.isFirstResponder(){
sportTextField.resignFirstResponder()
} else if periods.isFirstResponder(){
periods.resignFirstResponder()
} else if length.isFirstResponder() {
length.resignFirstResponder()
} else if noOfPlayers.isFirstResponder() {
noOfPlayers.resignFirstResponder()
} else if teamName.isFirstResponder() {
teamName.resignFirstResponder()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// set pickerview
self.pickerView = UIPickerView()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updatePicker), name: UITextFieldTextDidBeginEditingNotification, object: nil)
pickerView.showsSelectionIndicator = true
pickerView.delegate = self
// add pickerview for each field
sportTextField.inputView = pickerView
sportTextField.inputAccessoryView = toolBarSetUp()
periods.inputView = pickerView
periods.inputAccessoryView = toolBarSetUp()
length.inputAccessoryView = toolBarSetUp()
noOfPlayers.inputAccessoryView = toolBarSetUp()
teamName.inputAccessoryView = toolBarSetUp()
// add targets to fields to make sure fields aren't empty
teamName.addTarget(self, action: #selector(checkFields), forControlEvents: .EditingDidEnd)
sportTextField.addTarget(self, action: #selector(checkFields), forControlEvents: .EditingDidEnd)
periods.addTarget(self, action: #selector(checkFields), forControlEvents: .EditingDidEnd)
length.addTarget(self, action: #selector(checkFields), forControlEvents: .EditingDidEnd)
noOfPlayers.addTarget(self, action: #selector(checkFields), forControlEvents: .EditingDidEnd)
// if edited team then change nav title
if let team = teamToEdit {
title = "Edit Team"
teamName.text = team.name
sportTextField.text = team.sport
noOfPlayers.text = String(team.no_of_players)
periods.text = String(team.no_of_periods)
length.text = String(team.period_length)
doneBarButton.enabled = true
}
}
indent preformatted text by 4 spaces
Thanks for any help with this