Change textcolor with click on different button - swift

I have two IBAction and want to change of the text of two buttons who refer to these IBActions.
I can change with sender. the color of the own button. But not with the other button. How can I solve this? My Code doesnt work. It only changes the own color.
#IBAction func arminiaBielefeld(_ sender: UIButton) {
team = "arminia"
Bundesliga1.bildlink = "bundesliga1/arminia"
Bundesliga1.ligaIcon = "bundesliga1/bundesliga1"
sender.setTitleColor(.white, for: [])
augsburg.setTitleColor(.blue, for: [])
}
#IBAction func augsburg(_ sender: UIButton) {
team = "augsburg"
Bundesliga1.bildlink = "bundesliga1/augsburg"
Bundesliga1.ligaIcon = "bundesliga1/bundesliga1"
sender.setTitleColor(.white, for: [])
arminiaBielefeld.setTitleColor(.blue, for: [])
}
Screenshot added.

Try using the outlet name of the button instead of sender. Also do not have the name of the action identical to the name of the outlet.
Add the following two outlets to your view controller and connect them in storyboard:
#IBOutlet weak var arminiaBielefeld: UIButton!
#IBOutlet weak var augsburg: UIButton!
The following works:
#IBAction func arminiaBielefeldPressed(_ sender: Any) {
team = "arminia"
Bundesliga1.bildlink = "bundesliga1/arminia"
Bundesliga1.ligaIcon = "bundesliga1/bundesliga1"
arminiaBielefeld.setTitleColor(.white, for: [])
augsburg.setTitleColor(.blue, for: [])
}
#IBAction func augsburgPressed(_ sender: Any) {
team = "augsburg"
Bundesliga1.bildlink = "bundesliga1/augsburg"
Bundesliga1.ligaIcon = "bundesliga1/bundesliga1"
augsburg.setTitleColor(.white, for: [])
arminiaBielefeld.setTitleColor(.blue, for: [])
}

Related

If we click on the AddCommentsButton the AddCommentsTextView must enable. how to implement in swift iOS?

#IBOutlet weak var AddCommentsButton: UIButton!
#IBOutlet weak var AddCommentsTextView: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.AddCommentsButton.setTitle("Add Comments", for: UIControl.State.normal)
self.AddCommentsButton.setTitleColor(UIColor.blue, for: UIControl.State.normal)
AddCommentsTextView.rchDelegate = self as? RCHTextViewDelegate
AddCommentsTextView.delegate = self as? UITextViewDelegate
AddCommentsTextView.placeholder = "Leave a comment"
AddCommentsTextView.canShowBorder = true
AddCommentsTextView.addBorderWithCornerRadius(cornerRadius: 0, borderColor: .Gray, borderWidth: 0.5)
AddCommentsTextView.backgroundColor = UIColor.clear
self.AddCommentsTextView.font = UIFont.dynamicFont(control: .listKeyText)
self.AddCommentsTextView.textColor = UIColor.listKeyTextColor()
}
#IBAction func didTapAddCommentsButton(_ sender: Any) {
}
If you are looking for when you click on didTapAddCommentsButton button then the AddCommentsTextView Textview should show the cursor in the textview for entering the text then you can use:
#IBAction func didTapAddCommentsButton(_ sender: Any) {
self.AddCommentsTextView.becomeFirstResponder()
}
So that on button click it will enable textview cursor for entering purpose.
UPDATED:
If you want to remove focus from the text entry then use:
self.AddCommentsTextView.resignFirstResponder()

How to add button target function in IBAction method

I am using SWRevealViewController for side menu. while i click on menuBtn, im performing right toggle operation. I want the same when i swipe right Can any one Please Help me with it.
class Invoice: UIViewController {
#IBOutlet weak var menuBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let revealViewController = self.revealViewController()
menuBtn.addTarget(revealViewController, action: #selector(SWRevealViewController.rightRevealToggle(_:)), for: .touchUpInside)
}
#IBAction func swipeGesture(_ sender: UISwipeGestureRecognizer) {
print("Swiped")
//I want same action as i clicked on mentBtn
}
}
Something like this should work:
#IBAction func swipeGesture(_ sender: UISwipeGestureRecognizer) {
self.revealViewController().rightRevealToggle(self.menuBtn)
}

Moving data from Model to destination ViewController with segue

I am new to Swift and programming in general. I am building a quiz app. The app uses TopicsViewController to select a topic and segue to a QuestionsViewController. The questions for the various topics are stored as separate Swift Objects file. I would like to pick the Topic1 Question file when I press the topic1 button in TopicsViewController to segue into the QuestionsViewController. I would like to know how can I select the particular questions file QuestionBank1/QuestionBank2 when I select the particular topic upon segueing to the QuestionsViewController?
Navigation Pane :
Main.storyboard :
TopicsViewController:
import UIKit
class TopicsViewController: UIViewController, returnToTopicVCDelegate {
func goToTopicVC() {
}
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func goToQuestionsVCWhenPressed(_ sender: UIButton) {
performSegue(withIdentifier: "segueToQuestionVC", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segueToQuestionVC" {
let quizVC = segue.destination as! QuizViewController
quizVC.delegate = self
}
}
}
QuizViewController:
import UIKit
import QuartzCore
protocol returnToTopicVCDelegate{
func goToTopicVC()
}
class QuizViewController: UIViewController {
var delegate : returnToTopicVCDelegate?
//outlet for the question label and image view
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var questionImageView: UIImageView!
//outlet for the buttons
#IBOutlet weak var optionAButton: UIButton!
#IBOutlet weak var optionBButton: UIButton!
#IBOutlet weak var optionCButton: UIButton!
#IBOutlet weak var optionDButton: UIButton!
#IBOutlet weak var optionEButton: UIButton!
//outlets for the progress
#IBOutlet weak var questionCounter: UILabel!
#IBOutlet weak var scoreLabel: UILabel!
var allQuestions = QuestionBank()
var selectedAnswer : Int = 0 // answer selected by the subject
var questionNumber: Int = 0
var score: Int = 0
// functions executed after an answer is picked
#IBAction func answerPressed(_ sender: UIButton) {
if sender.tag == selectedAnswer {
print("correct answer")
sender.backgroundColor = .green
score += 1
} else {
print("wrong")
sender.backgroundColor = .red
print("\(allQuestions.list[questionNumber].correctAnswer)")
//the following two lines change the right answer button to green using the tag value of the button
let correctAnswerButton = view.viewWithTag(selectedAnswer) as? UIButton
correctAnswerButton?.backgroundColor = UIColor.green
}
}
#IBAction func GoToNextQuestion(_ sender: UIButton) {
questionNumber += 1
nextQuestion()
}
// selects a new questions and updates the score
func nextQuestion(){
if questionNumber <= allQuestions.list.count - 1 {
questionLabel.text = allQuestions.list[questionNumber].question
questionImageView.image = UIImage(named: (allQuestions.list[questionNumber].questionImage))
optionAButton.setTitle(allQuestions.list[questionNumber].optionA, for: UIControlState.normal)
optionBButton.setTitle(allQuestions.list[questionNumber].optionB, for: UIControlState.normal)
optionCButton.setTitle(allQuestions.list[questionNumber].optionC, for: UIControlState.normal)
optionDButton.setTitle(allQuestions.list[questionNumber].optionD, for: UIControlState.normal)
optionEButton.setTitle(allQuestions.list[questionNumber].optionE, for: UIControlState.normal)
selectedAnswer = allQuestions.list[questionNumber].correctAnswer
updateUI()
} else {
let alert = UIAlertController(title: "Great!", message: "Do you want to start over?", preferredStyle: .alert)
let restartAction = UIAlertAction(title: "Restart", style: .default) {(UIAlertAction) in
self.restartQuiz()
}
alert.addAction(restartAction)
present(alert, animated: true, completion: nil)
}
}
func updateUI(){
scoreLabel.text = "score: \(score)"
questionCounter.text = "\(questionNumber + 1)/\(allQuestions.list.count)"
}
func restartQuiz(){
score = 0
questionNumber = 0
nextQuestion()
}
#IBAction func goBackToTopicsVC(_ sender: Any) {
delegate?.goToTopicVC()
dismiss(animated: true, completion: nil)
}
}
You can use the following steps :
1- Add a segue from TopicsViewController to QuestionsViewController and give the segue "Identifier Name " from Attributes inspector.
2- Add a variable in QuestionsViewController for the topic lets name it "topicType".
3- Override the below function in TopicsViewController and send the name of the topic with the segue:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Identifier Name" {
if let destinationviewController = segue.destination as? QuestionsViewController , let buttonPressed = sender as? UIButton {
destinationviewController.topicType = buttonPressed.currentTitle!
}
}
}
4- For each button in TopicsViewController , get the button action and type the following function in it :
#IBAction func topicButton(_ sender: UIButton) {
performSegue(withIdentifier: "Identifier Name", sender: nil)
}
I hope this helps you .

Passing a variable from a customCell.xib's button to another UIViewController

My custom cell has a button that when clicked, the user can be taken to another ViewControler. That button has a titleLabel with the String of a user id. What I want to do is take the user to a new UIViewController, passing that clicked buttons's titleLabel (user id) to a variable on the new View Controller. That way, I can use that variable (user id) get further information from firebase and display it on the UI View controller.
on the .xib of the custom cell, I print the UID to make sure each button prints with the correspondent ID, which it does. I can't figure out a way to pass that ID to a new ViewController.
I tried researching online and I found out you can't do prepare(for segue) or performsegue(WithIdentifier) on a customCell.xib.
I tried doing delegates and then protocols but still couldn't get it to work. I am new with Swift. Any help would be great, thank you!
This is the customCell.Xib's Swift file:
class CustomCellTableViewCell: UITableViewCell {
#IBOutlet weak var postImage: UIImageView!
#IBOutlet weak var nameLbl: UILabel!
#IBOutlet weak var descriptionLbl: UITextView!
#IBOutlet weak var profileImageBtn: UIButton!
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var view: UIView!
var btnSelected : Bool = false
var vcInstance: ProfilesTableVC?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
view.clipsToBounds = true
view.layer.cornerRadius = view.frame.size.width / 2
profileImage.layer.cornerRadius = profileImage.frame.size.width / 2
descriptionLbl.alpha = 0.7
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
#IBAction func profileBtnPressed(_ sender: Any) {
let passValue = UserProfileVC()
let profileTvC = ProfilesTableVC()
print (profileImageBtn.titleLabel!.text!)
var id = (profileImageBtn.titleLabel!.text!)
profileTvC.didSelectProfileBtn(senderID: id)
}
This is the tableViewController, where I everything gets loaded (not where I want to pass the value). I tried passing the value here and then do a prepareForSegue to pass the value to the new UIViewController but the value becomes nil after the segue happens. I am just including code where the .xib call the function from the table view.
class ProfilesTableVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate{
let cell = CustomCellTableViewCell()
func didSelectProfileBtn(senderID: String) {
senderIDArray.append(senderID)
var index = senderIDArray.count - 1
selectedCellUserID = senderIDArray[index]
performSegue(withIdentifier: "showSendersProfile", sender: Any?.self)
}
This is the UIViewController where I want to pass the variable and display further information from Firebase using that ID
import UIKit
import Firebase
class UserProfileVC: UIViewController {
let customCell = CustomCellTableViewCell()
let profileTvC = ProfilesTableVC()
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var nameLbl: UILabel!
var delegate : Any?
var getName = String()
var getsenderID = String()
let userDataRef = Database.database().reference().child("Users")
override func viewDidLoad() {
super.viewDidLoad()
print("ID is: \(profileTvC.selectedCellUserID)")
let sender = getsenderID
print(sender)
}
}
If you don't want to use protocols, you can addTarget to the button in the tableView - cellForRowAt method, also in that method you set the tag to the row index value.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let profileCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! MoviewReviewCell
reviewCell.profileImageBtn.tag = indexPath.row
reviewCell.profileImageBtn.addTarget(self, action: #selector(tappedOnXibCellButton), for: .touchUpInside)
return reviewCell
}
#objc func tappedOnXibCellButton(sender: UIButton) {
print(sender.tag)
performSegue(withIdentifier: reviewListToDetails, sender: sender.tag)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let identifier = segue.identifier
if identifier == "segueName" {
let destViewController = segue.destination as! DestinationClassViewController
let selectedIndex = sender as! Int
let profileId = profilesList[selectedIndex].id
destViewController.profileId = profileId
}
}
You seem to create a NEW ProfilesTableVC, and try to perform the segue on. The newly created one is not on your view stack, and not from your storyboard.
You could add this while returned cellForRowAt (at the ProfilesTableVC of course):
cell.vcInstance = self
Then in the button click
#IBAction func profileBtnPressed(_ sender: Any) {
print (profileImageBtn.titleLabel!.text!)
var id = (profileImageBtn.titleLabel!.text!)
vcInstance?.didSelectProfileBtn(senderID: id)
}
You can do it with protocols/delegates. I think you tried but there is something wrong with your trial.
Define a callback delegate:
protocol CustomCellDelegate: AnyObject {
func customCell(didSelectButton name: String)
}
You will notice extending AnyObject. This is to allow weak references, try to read about Swift ARC
Then, in your cell:
weak var delegate: CustomCellDelegate?
Then in the profileBtnPressed(_ sender: Any)
#IBAction func profileBtnPressed(_ sender: Any) {
var id = (profileImageBtn.titleLabel!.text!)
delegate?.customCell(didSelectButton: id)
}
When dequeing the cell:
(cell as? CustomCellTableViewCell)?.delegate = self

perform segue with the same button to two different viewControllers based on information in uitextfield

I am trying to make my view controller segue to two different view controllers with the same button. But i want the segue's to be done based on information that is in an uitextfield. e.g = if the textfield contains the right information then i will need the segue to perform to segue to viewControllerA if the information does not match my array of strings, ViewController will segue to viewControllerB.
Sample code:
#IBOutlet var pcTextField: UITextField!
#IBOutlet var odButton: UIButton!
var activePcText = ["over", "left", "weak", "never"]
override func viewDidLoad() {
super.viewDidLoad()
pcTextField.delegate = self
let tapRecognizer = UITapGestureRecognizer(target: self, action: "hideKeyboard")
view.addGestureRecognizer(tapRecognizer)
odButton.hidden = true
self.pcTextField.addTarget(self, action: "pcEmpty", forControlEvents: UIControlEvents.EditingChanged)
}
#IBAction func odButton(sender: AnyObject) { }
I tried to implement an if statement as..
#IBAction func odButton(sender: AnyObject) {
if pcTextField.text!.containsString(activePcText) { }
}
I just get an error saying:
Cannot convert value of type '[String]' to expected argument type 'String'
#IBOutlet weak var pcTextField: UITextField!
let activePcText = ["over", "left", "weak", "never"]
#IBAction func buttonPressed(sender: UIButton) {
let text = pcTextField.text?.lowercaseString ?? ""
let destination = activePcText.map { $0.lowercaseString }.contains(text) ? "viewControllerA" : "viewControllerB"
performSegueWithIdentifier(destination, sender: self)
}
This makes it case insensitive.
This is an example of a prepareForSegue method that would accomplish what it sounds like you want to do
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "segueIdentifier" {
if myTextField.text = "words inside text field" {
let controller = segue.destinationViewController as! MyViewController
} else if myTextField.text = "different words in text field" {
let controller = segue.destinationViewController as! MyOtherViewController
}
}
}
So depending on the text inside of myTextField, the segue will be performed to either MyViewController or MyOtherViewController
And then in the #IBAction of whichever button you want to trigger the segue you would add performSegueWithIdentifier("segueIdentifier")