I need to set constraints for a UILabel, but whenever I try to add a constraint for my UITableViewCell it messes up, and the element goes to the top left corner it seems
Here's how I set up my UI elements
Here's how it looks like when I run in a simulator
"Food" is the "English Meaning" UILabel
Here's my code for the cell file that's generated with the xib
class ReusableCell: UITableViewCell {
#IBOutlet weak var arabicMeaning: UILabel!
#IBOutlet weak var englishMeaning: UILabel!
#IBOutlet weak var upvoteButton: UIButton!
#IBOutlet weak var downvoteButton: UIButton!
#IBOutlet weak var upvoteCount: UILabel!
#IBOutlet weak var downvoteCount: UILabel!
var upFlag = true
var downFlag = true
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
}
static func nib() -> UINib{
return UINib(nibName: K.ReusableCell, bundle: nil)
}
#IBAction func ReviewPressed(_ sender: UIButton) {
if upFlag && downFlag{
if sender == upvoteButton{
upvoteCount.text = String(Int(upvoteCount.text!)! + 1)
}
else {
downvoteCount.text = String(Int(downvoteCount.text!)! + 1)
}
}
else if sender == upvoteButton && upFlag{
upFlag = false
downFlag = true
upvoteCount.text = String(Int(upvoteCount.text!)! + 1)
}
else if sender == downvoteButton && downFlag{
upFlag = true
downFlag = false
downvoteCount.text = String(Int(downvoteCount.text!)! + 1)
}
}
}
Related
I've been working through a project and have gotten most of the functionality straight, however there's one part that continues to stump me. I am using MVC format, and I have a two view controllers (one profile and one game). When progress is made on the game, the proper changes to game view controller show (i.e. button disappears and UI background color changes colors). However, when I segue to profile view controller using 'back' on navigation bar and return to the game view controller, the game view controller returns to the default without reflecting game progress.
I've tried unwinding segue, making a delegate going from view controller to model responsible for game play, adjusting my game logic, and trying viewdidload and viewwillappear. I'm running out of ideas.
Here are samples of pertinent code:
Game View Controller
import UIKit
import Firebase
class GameController: UIViewController, BrainDelegate, UITextFieldDelegate {
#IBOutlet weak var dateUsername: UILabel!
#IBOutlet weak var questionText: UILabel!
#IBOutlet weak var scoreText: UILabel!
#IBOutlet weak var answerOne: UITextField!
var userListOne: [String] = []
#IBOutlet weak var answerTwo: UITextField!
#IBOutlet weak var answerThree: UITextField!
#IBOutlet weak var answerFour: UITextField!
#IBOutlet weak var enterOne: UIButton!
#IBOutlet weak var enterTwo: UIButton!
#IBOutlet weak var enterThree: UIButton!
#IBOutlet weak var enterFour: UIButton!
#IBOutlet weak var feedbackText: UILabel!
#IBAction func logoutPressed(_ sender: UIBarButtonItem) {
do {
try Auth.auth().signOut()
navigationController?.popToRootViewController(animated: true)
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
}
let db = Firestore.firestore()
var questions = [Question]()
var Brain = Brain()
var delegate: brainDelegate?
//variables for delegate with json data
var questioner : String?
var dater : String?
var a1 : String?
var a2 : String?
var a3 : String?
var a4 : String?
//For game play
var answer1: String?
var answer2: String?
var answer3: String?
var answer4: String?
var puzzlesCompleted = "0"
func didUpdateBrain(narratives: [Question]) {
self.questions = narratives
}
func didFailWithError(error: Error) {
print(error)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
minketBrain.delegate = self
answerOne.delegate = self
answerTwo.delegate = self
answerThree.delegate = self
answerFour.delegate = self
if let localData = minketBrain.readLocalJSONFile(forName: K.minketClues) {
minketBrain.parseJSON(jsonData: localData)
}
//Transfer data from Profile Controller
self.questionText.text = questioner
self.dateUsername.text = dater
self.answer1 = a1
self.answer2 = a2
self.answer3 = a3
self.answer4 = a4
}
override func viewWillAppear(_ animated: Bool) {
view.reloadInputViews()
answerOne.text = userListOne.last
}
//MARK: - Button Logic
#IBAction func enterPressed(_ sender: UIButton) {
enterPressedOne()
allRight()
}
//Other buttons replicate the same code above
//MARK: - Correct Answer Logic
func allRight(){
if answerOne.backgroundColor == UIColor.green && answerTwo.backgroundColor == UIColor.green && answerThree.backgroundColor == UIColor.green && answerFour.backgroundColor == UIColor.green {
feedbackText.text = K.congratsText
puzzlesCompleted = "1"
if let allAnswer = scoreText.text, let userName = Auth.auth().currentUser?.email{
db.collection(K.FStore.collectionName).addDocument(data: [K.FStore.userName:userName, K.FStore.clueDate:dateUsername.text!, K.FStore.totalPoints:allAnswer, K.FStore.completionField:puzzlesCompleted]) { (error) in
if let e = error{
print("There was an error in data collection to Firestore \(e)")
}else{
print("Successfully saved data")
}
}
}
}
}
//MARK: - Update UI-Each Question
func enterPressedOne(){
if let item = answerOne.text, item.isEmpty == true { // need to make sure we have something here
userListOne.append(item) // store it in our data holder
print(userListOne)
}
if answerOne.text == self.answer1!.lowercased(){
answerOne.backgroundColor = UIColor.green
enterOne.isHidden = true
answerOne.isEnabled = false
}else{
answerOne.backgroundColor = UIColor.red
}
}
}
Unwind segue function in my profile controller
#IBAction func unwindToDestinationViewController (sender: UIStoryboardSegue){
print("Unwind")
}
I'm new to swift, I would like to change my UIViewController background color from the custom UIToolbar that I already created at XIB. I also already add the custom toolbar to my keyboard. How can i do that?
In my toolbar, I have a button that indicates the color that the user can set to the background color of UIViewController.
My Custom Toolbar
Class for custom toolbar, ColorToolbar.swift
import UIKit
class ColorToolbar: UIToolbar {
#IBOutlet weak var purpleButton: UIBarButtonItem!
#IBOutlet weak var blueButton: UIBarButtonItem!
#IBOutlet weak var greenButton: UIBarButtonItem!
#IBOutlet weak var yellowButton: UIBarButtonItem!
#IBOutlet weak var redButton: UIBarButtonItem!
var makeNotesVC = MakeNotesVC()
var selectedColor : UIColor = UIColor.clear
override func awakeFromNib() {
super.awakeFromNib()
setupButtonColor()
}
#IBAction func colorButtonPressed(_ sender: UIBarButtonItem) {
guard let color = sender.tintColor else {return}
selectedColor = color
print(selectedColor)
makeNotesVC.view.backgroundColor = selectedColor
}
#objc func changeBgColor(){
makeNotesVC.view.backgroundColor = selectedColor
}
private func setupButtonColor(){
purpleButton.tintColor = Constants.TintColorButton.purple
blueButton.tintColor = Constants.TintColorButton.blue
greenButton.tintColor = Constants.TintColorButton.green
yellowButton.tintColor = Constants.TintColorButton.yellow
redButton.tintColor = Constants.TintColorButton.red
}
}
Class for UIViewController that i want to change background color, MakeNotesVC.swift
import UIKit
class MakeNotesVC: UIViewController {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
#IBOutlet weak var titleTextfield: UITextField!
#IBOutlet weak var notesText: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
addColorbutton()
}
#IBAction func saveButtonPressed(_ sender: UIBarButtonItem) {
let newNote = Note(context: context)
newNote.title = titleTextfield.text
newNote.text = notesText.text
self.navigationController?.popToRootViewController(animated: true)
}
func addColorbutton(){
// TODO : Add Color Options Toolbar
//Register custom toolbar
let toolbar = UINib(nibName: "Toolbar", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! ColorToolbar
toolbar.sizeToFit()
//Add toolbar to keyboard
titleTextfield.inputAccessoryView = toolbar
notesText.inputAccessoryView = toolbar
}
}
Add protocol at your custom tool bar
protocol BackgroundColorControlDelegate: AnyObject {
func changeBackgroundColor(sender:Any, color: UIColor)
}
import UIKit
class ColorToolbar: UIToolbar {
#IBOutlet weak var purpleButton: UIBarButtonItem!
#IBOutlet weak var blueButton: UIBarButtonItem!
#IBOutlet weak var greenButton: UIBarButtonItem!
#IBOutlet weak var yellowButton: UIBarButtonItem!
#IBOutlet weak var redButton: UIBarButtonItem!
var makeNotesVC = MakeNotesVC()
var selectedColor : UIColor = UIColor.clear
weak var delegate: BackgroundColorControlDelegate?
override func awakeFromNib() {
super.awakeFromNib()
setupButtonColor()
}
#IBAction func colorButtonPressed(_ sender: UIBarButtonItem) {
guard let color = sender.tintColor else {return}
selectedColor = color
print(selectedColor)
delegate?.changeBackgroundColor(sender: self, color: color)
}
#objc func changeBgColor(){
makeNotesVC.view.backgroundColor = selectedColor
}
private func setupButtonColor(){
purpleButton.tintColor = Constants.TintColorButton.purple
blueButton.tintColor = Constants.TintColorButton.blue
greenButton.tintColor = Constants.TintColorButton.green
yellowButton.tintColor = Constants.TintColorButton.yellow
redButton.tintColor = Constants.TintColorButton.red
}
}
call delegate from MakeNotesVC
import UIKit
class MakeNotesVC: UIViewController {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
#IBOutlet weak var titleTextfield: UITextField!
#IBOutlet weak var notesText: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
addColorbutton()
}
#IBAction func saveButtonPressed(_ sender: UIBarButtonItem) {
let newNote = Note(context: context)
newNote.title = titleTextfield.text
newNote.text = notesText.text
self.navigationController?.popToRootViewController(animated: true)
}
func addColorbutton(){
// TODO : Add Color Options Toolbar
//Register custom toolbar
let toolbar = UINib(nibName: "Toolbar", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! ColorToolbar
toolbar.sizeToFit()
toolbar.delegate = self
//Add toolbar to keyboard
titleTextfield.inputAccessoryView = toolbar
notesText.inputAccessoryView = toolbar
}
}
extension MakeNotesVC: BackgroundColorControlDelegate {
func changeBackgroundColor(sender:Any, color: UIColor) {
view.backgroundColor = color
}
}
I want to change uilabel value and show uiview that has hide like a popup windows.
When I touch a button, that code print "setPopupView 0".
but doesn't show settingView.
and I touch a button again.
print "setPopupView 0" and show settingView.
so When "settingLabelValueUnit text" has changed not show settingView,
but when "settingLabelValueUnit text" has not changed show settingView.
(It means "settingLabelValue text" is same as input value)
I don't know why.
Anyone can help me?
Thank you
here is my swift code.
class ViewController: UIViewController {
#IBOutlet weak var workoutScrollView: UIScrollView!
#IBOutlet weak var settingView: UIView!
#IBOutlet weak var settingLabelValueUnit: UILabel!
#IBOutlet weak var imgSettingBGcal: UIImageView!
#IBOutlet weak var imgSettingBGdis: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.imgSettingBGcal.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(calSettingClick)))
self.imgSettingBGdis.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(disSettingClick)))
}
func calSettingClick(sender: UITapGestureRecognizer) {
setPopupView(0)
}
func disSettingClick(sender: UITapGestureRecognizer) {
setPopupView(1)
}
func showPopup (_ settype:Int) {
switch settype {
case 0:
print("setPopupView 0")
self.settingLabelValueUnit.text = "Set1"
self.workoutScrollView.isHidden = true
self.settingView.isHidden = false
case 1:
print("setPopupView 0")
self.settingLabelValueUnit.text = "Set2"
self.workoutScrollView.isHidden = true
self.settingView.isHidden = false
}
}
}
For the radioButtons I have used Class in the button and for the indicator to buttons i have used the labels.
These are My TextView
#IBOutlet weak var TextViewEveryNewMessage: UILabel!
#IBOutlet weak var TextViewWeekly: UILabel!
#IBOutlet weak var TextViewDaily: UILabel!
#IBOutlet weak var TextViewMonthly: UILabel!
These are my Radio Buttons
#IBOutlet weak var RadioBtnMonthly: SSRadioButton!
#IBOutlet weak var RadioBtnWeekly: SSRadioButton!
#IBOutlet weak var RadioBtnDefaultChecked: SSRadioButton!
#IBOutlet weak var RadioBtnDaily: SSRadioButton!
As soon as i press the ok button i need to save the checkedRadio Button text somewhere and i have done it like this.
#IBAction func OkButton(sender: UIButton) {
SwiftSpinner.show(kLoadingText)
if RadioBtnDefaultChecked.selected{
preferencesConditions.notificationFrequency = self.TextViewEveryNewMessage.text
}else if RadioBtnDaily.selected{
preferencesConditions.notificationFrequency = self.TextViewDaily.text
}else if RadioBtnWeekly.selected{
preferencesConditions.notificationFrequency =
self.TextViewWeekly.text
}else{
preferencesConditions.notificationFrequency = self.TextViewMonthly.text
}
Is this correct way i am doing.Or there are any other approach. Please suggest me.
Instead of assigning a value for preferencesConditions.notificationFrequency in OkButton(sender: UIButton), you should do it in each of the SSRadioButton buttons and that's by calling SSRadioButtonControllerDelegate - didSelectButton:
func didSelectButton(aButton: UIButton?) {
print(aButton)
if aButton === RadioBtnDefaultChecked {
preferencesConditions.notificationFrequency = self.TextViewEveryNewMessage.text
}else if aButton === RadioBtnDaily {
preferencesConditions.notificationFrequency = self.TextViewDaily.text
}else if aButton === RadioBtnWeekly {
preferencesConditions.notificationFrequency =
self.TextViewWeekly.text
}else{
preferencesConditions.notificationFrequency = self.TextViewMonthly.text
}
}
Don't forget to conform the delegate to the viewController:
var radioButtonController: SSRadioButtonsController?
override func viewDidLoad() {
radioButtonController = SSRadioButtonsController(buttons: RadioBtnDefaultChecked, RadioBtnDaily, RadioBtnWeekly)
radioButtonController!.delegate = self
radioButtonController!.shouldLetDeSelect = true
}
The IBAction should be like:
#IBAction func OkButton(sender: UIButton) {
SwiftSpinner.show(kLoadingText)
}
For more information, check SSRadioButtonsController.
Hope this helped.
Just learning so I am sure there are much better ways to code what I have so far. Anyways, I have a simple task list that is saved to core data. You can segue to another VC where you can edit or create new task. I wanted to be able to put a uiswitch in the custom cell that would allow you to set the task as complete and then reload the tableview. I have searched all over and found this Select UITableView's row when tapping on its UISwitch in Swift but can't seem to translate a solution. Any help would be great.
enter image description here
I am not sure if I am supposed to code the save within the custom cell or just or pass delegate.
Here is my custom cell
protocol SettingCellDelegate : class {
func didChangeSwitchState(sender: TaskCell, isOn: Bool)
}
class TaskCell: UITableViewCell {
var delegate: SettingCellDelegate!
#IBOutlet weak var taskImage: UIImageView!
#IBOutlet weak var arrowImage: UIImageView!
#IBOutlet weak var dueDateLabel: UILabel!
#IBOutlet weak var dueDateValue: UILabel!
#IBOutlet weak var dueTimeLabel: UILabel!
#IBOutlet weak var dueTimeValue: UILabel!
#IBOutlet var taskCellStatus: UITextField!
#IBOutlet var taskCellSwitchDisplay: UISwitch!
#IBAction func taskCellSwitchAction(sender: AnyObject) {
if (taskCellSwitchDisplay.on) {
taskCellStatus.text = "Completed"
} else {
taskCellStatus.text = "Active"
}
}
#IBOutlet weak var taskNameValue: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
delegate = self
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
taskCellSwitchDisplay.addTarget(self, action: "switchChanged:", forControlEvents: UIControlEvents.ValueChanged)
}
func configureCell(task: Tasks) {
taskImage.image = UIImage(named: "Icon.png")
arrowImage.image = UIImage(named: "arrow_filled.png")
dueDateLabel.text = "Due Date:"
dueDateValue.text = task.taskDate
dueTimeLabel.text = "Due Time:"
dueTimeValue.text = task.taskTime
taskNameValue.text = task.taskName
taskCellStatus.text = task.status
//taskCellStatus.hidden = true
if (taskCellStatus.text == "Completed") {
taskCellSwitchDisplay.on = true
} else {
taskCellSwitchDisplay.on = false
}
}
func switchChanged(taskCellSwitchDisplay: UISwitch) {
_ = taskCellSwitchDisplay.on
if taskCellSwitchDisplay.on == true {
let switchValue = "Completed"
print("Switch Variable: \(switchValue)")
delegate.didChangeSwitchState(self, isOn: true)
} else {
let switchValue = "Active"
print("Switch Variable: \(switchValue)")
delegate.didChangeSwitchState(self, isOn: false)
}
}
Here is where I am getting the delegate in my tableview
extension TaskCell: SettingCellDelegate {
func didChangeSwitchState(sender: TaskCell, isOn: Bool) {
if isOn == true {
print("true")
} else {
print("false")
}
}