How to save index and rating values both? - ios

Here I had used HCSStarRatingview for rating and here i had implemented it in table view so that i need to get the selected particular rating value and need to save according to its index and there should be also in need to change the saved value later also and need to insert in the selected index can anyone help me how to implement this ?
Here is my code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "ratingCell", for: indexPath) as! ratingCell
return cell
}
else if indexPath.section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "reviewCell", for: indexPath) as! AddaReviewTableViewCell
let arr = reviewModel[indexPath.row]
cell.reviewTypeLabel.text = arr.ratingCode
cell.starRatingControl.tag = indexPath.row
cell.starRatingControl.addTarget(self, action: #selector(RatingControlAction(_:)), for: .touchUpInside)
return cell
}
else{
let cell = tableView.dequeueReusableCell(withIdentifier: "reviewInputCell", for: indexPath) as! reviewInputCell
nickName = cell.nameTextField.text
summary = cell.summaryTextField.text
review = cell.reviewTextView.text
cell.submitReviewButton.addTarget(self, action: #selector(submitReviewAction(_:)), for: .touchUpInside)
return cell
}
}
func isValidFirstname(testStr:String) -> Bool {
let firstnameRegEx = "^[a-zA-Z]+$"
let firstnameTest = NSPredicate(format:"SELF MATCHES %#", firstnameRegEx)
let result = firstnameTest.evaluate(with: testStr)
return result
}
func RatingControlAction(_ sender:Any){
let buttonPosition = (sender as AnyObject).convert(CGPoint(), to: tableDetails)
let index = tableDetails.indexPathForRow(at: buttonPosition)
print(String(format: "Changed rating to %.1f", (sender as AnyObject as! CVarArg)))
}
And screenshot for this is shown here

Why don't you create a struct which can hold two values
Declare a struct
struct Struct_Row_Rating {
var row: String
var rating: Int
init(row: String , rating: Int ) {
self.row = row
self.rating = rating
}}
Declare an array
var arrayAdaptor = [Struct_Row_Rating]()
Append array like this
arrayAdaptor.append(Struct_Row_Rating(row: IndexPath.row, rating: 3)
You can retrieve the value by
var index1 = arrayAdaptor[1].rating // use dynamic value here
More on struct

Related

UISearchController takes the wrong item

this is my code here I touch on + before search It gives correct product. but the problem is after search, it gives previous product not the correct product
after searching UISearchController looks up self.tableView
search is working finely
table view
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Configure the cell...
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "MasterViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MasterViewCell else {
fatalError("The dequeued cell is not an instance of OutletViewCell.")
}
// Fetches the appropriate meal for the data source layout.
var product = products[indexPath.row]
if isFiltering {
product = filteredProducts[indexPath.row]
} else {
product = products[indexPath.row]
}
cell.productName.text = product.productDescription
cell.availQty.text = "Avail. Qty:" + String(product.stock)
cell.productPrice.text = "Price: " + String(product.defaultSellPrice)
cell.addItem.tag = indexPath.row
cell.addItem.addTarget(self, action: #selector(buttonTapped(button:)), for: .touchUpInside)
orderDetails.forEach { detail in
// print(word.price)
if detail.key == product.id {
cell.AddedQty.text = "Qty :" + String(detail.value.qty)
}
}
return cell
}
here is buttonTapped function
#objc func buttonTapped(button: UIButton) {
// print("Button pressed " + String(button.tag))
let product=products[button.tag]
print(product.productDescription)
showAlert(product: product)
}
In your buttonTapped function, you also need to check if the data isFiltered or not
#objc func buttonTapped(button: UIButton) {
let productData = isFiltering ? filteredProducts[indexPath.row] : products[indexPath.row]
showAlert(product: productData)
}

How to remove the append data and check at each section in tableview in swift

I have tableview (grouped).
I have sections.
So each header i have display questions.
EX:-
.How are u?
So the options are:-Fine and not well.
This is the screen shot.
This is my code:-
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
print("Section \(indexPath.section), Row : \(indexPath.row)")
if tableView == tableview{
let cell = tableview.cellForRow(at: indexPath) as? QuestionListCell
let model = questionViewModel.datafordisplay(atindex: indexPath)
print(model.isSelected)
cell?.setOptions(OptionsSelected:questionViewModel.datafordisplay(atindex: indexPath))
print(model.isSelected)
questionViewModel.isselected = model.isSelected!
let section = indexPath.section
let index = indexPath.row
print(section)
print(index)
if !questionViewModel.selectedIndexPaths.contains(indexPath) {
questionViewModel.selectedIndexPaths.append(indexPath)
print(questionViewModel.selectedIndexPaths.append(indexPath))
let questionModel = questionViewModel.titleForHeaderInSection(atsection: section)
print(questionModel.question)
print(questionModel.buttontype)
questionViewModel.button = questionModel.buttontype
if questionViewModel.button == "1"{
// cell?.imagebutton.imageView?.image = UIImage(named: "checkbox_uncheck.png")
cell?.imagebutton.setImage(UIImage(named: "checkbox_check.png"), for: .normal)
// tableview.cellForRow(at: indexPath)?.accessoryType = .none
self.selected = 1
questionViewModel.imagename = "1"
}
else if questionViewModel.button == "2"{
self.selected = 1
// cell?.imagebutton.imageView?.image = UIImage(named: "radio_uncheck.png")
cell?.imagebutton.setImage(UIImage(named: "radio_check.png"), for: .normal)
// tableview.cellForRow(at: indexPath)?.accessoryType = .none
questionViewModel.imagename = "2"
}
questionViewModel.question = questionModel.question
questionViewModel.questionlist(answer: questionViewModel.question!)
let cell = tableview.cellForRow(at: indexPath) as? NH_QuestionListCell
let model = questionViewModel.datafordisplay(atindex: indexPath)
print(model.values)
questionViewModel.answer(answer: model.values!)
let value: Int = questionModel.id
let string = String(describing: value)
//let x: Int? = Int(model.id)
questionViewModel.question_id = string
questionViewModel.question(answer: questionViewModel.question_id!)
print(questionModel.id)
}
print(questionViewModel.button)
}
So according to this .I have 3 array .
1.to append the questions in an array.
2.To append the id in an array.
3.To append the answers in an array.
So according to this output as below.
For question1.
I selected 1st option
So the output comes as:-
questionarray:["Gender"]
answerarray:["fine"]
questionid:["1"]
But after selecting i decide to select the 2nd option.So first i should remove the append data from the 3 arrays.Then needed to append the current data.So the data should as below.
questionarray:["Gender"]
answerarray:["not well"]
questionid:["1"]
So how to do here.How to check here.Same way i need at every section .So to do?

Value comes as optional("myvalue"), how to get only value without the optional [duplicate]

This question already has answers here:
What is an optional value in Swift?
(15 answers)
Closed 5 years ago.
I am getting my value as Value comes as optional("myvalue"),But how can i get only value without the optional. I have tried a lot but not getting point, any help will be appreciated highly. The thing is that i am using Firebase as database and getting values in database.
I want to get value of Gender, Blood and country code.
Firebase connectivity
ref.child("user_registration").child(UserID!).setValue(["username": fullName.text!, "email": emailTextField.text!, "contact": numberText.text!, "city": myCity.text!, "state":countryText.text!, "gender": genderGroup, "blood": bloodGroup,"code": countryGroup])
Other code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == tableViewB {
let cell = tableViewB.dequeueReusableCell(withIdentifier: "blood", for: indexPath)
cell.textLabel!.text = dropDownList[indexPath.row]
return cell
}
else if tableView == genderT {
let cell = genderT.dequeueReusableCell(withIdentifier: "gender", for: indexPath)
cell.textLabel!.text = genderL[indexPath.row]
return cell
}
else {
let cell = countryT.dequeueReusableCell(withIdentifier: "country", for: indexPath) as! CountryTableViewCell
cell.countryLabel.text = countryL[indexPath.row]
cell.flagImage.image = countryFlags[indexPath.row]
return cell
}
}
var bloodGroup : String?
var genderGroup : String?
var countryGroup : String?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == tableViewB {
let selectedData = dropDownList[indexPath.row]
buttonB.setTitle(selectedData, for: .normal)
self.tableViewB.isHidden = true
self.flag = 1
let indexPath = tableViewB.indexPathForSelectedRow
let currentCell = tableViewB.cellForRow(at: indexPath!)! as UITableViewCell
bloodGroup = currentCell.textLabel!.text!
print("\(bloodGroup)")
}
else if tableView == genderT {
let selectedDataG = genderL[indexPath.row]
genderB.setTitle(selectedDataG, for: .normal)
self.genderT.isHidden = true
self.flag = 1
let indexPath = genderT.indexPathForSelectedRow
let currentCell = genderT.cellForRow(at: indexPath!)! as UITableViewCell
genderGroup = currentCell.textLabel!.text!
print("\(genderGroup)")
}
else {
let selectedDataG = countryL[indexPath.row]
countryB.setTitle(selectedDataG, for: .normal)
self.countryT.isHidden = true
self.flag = 1
let indexPath = countryT.indexPathForSelectedRow
let currentCell = countryT.cellForRow(at: indexPath!)! as! CountryTableViewCell
countryGroup = currentCell.countryLabel.text!
let finalFlag = currentCell.flagImage.image!
print("\(finalFlag)" + "\(countryGroup)")
}
}
<br>
Console
com.apple.MobileAsset.TextInput.SpellChecker
Optional("male")
Optional("A+")
<UIImage: 0x600000295950>, {96, 64}Optional("+92")
fatal error: unexpectedly found nil while unwrapping an Optional value
Try this :
Print object
print(bloodGroup ?? "")
And
cell.textLabel!.text = (dropDownList[indexPath.row] ?? "")
Please write
if tableView == tableViewB {
let cell = tableViewB.dequeueReusableCell(withIdentifier: "blood", for: indexPath)
cell.textLabel!.text = dropDownList[indexPath.row] as! String
return cell
}
Instead of
if tableView == tableViewB {
let cell = tableViewB.dequeueReusableCell(withIdentifier: "blood", for: indexPath)
cell.textLabel!.text = dropDownList[indexPath.row]
return cell
}
In table view cellForRowAt method.

issue of reuse collection view cell

I have stuck on this issue for 2 days. I don't know why.
I have a collection view for shopping cart purpose. there is a stepper on the reusable cell with a valueChanged event.
I use the following code to handle the problem:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! CartCollectionViewCell
cell.name?.text = cart[indexPath.row].value[0]
let url = URL(string: (baseUrl + (cart[indexPath.row].value[1])))
cell.img.setImageWith(url!)
cell.price?.text = "$" + (cart[indexPath.row].value[2])
cell.remove.addTarget(self, action: #selector(cartViewController.remove_from_cart(sender:)), for: .touchDown)
cell.remove.tag = indexPath.row
cell.qty.value = Double(cart[indexPath.row].value[3])!
cell.qty.addTarget(self, action: #selector(cartViewController.stepperValueChanged(stepper:)), for: .valueChanged)
cell.qty.tag = indexPath.row
return cell
}
func stepperValueChanged(stepper: GMStepper) {
let pos = stepper.convert(CGPoint.zero, to: collection)
let indexPath = collection.indexPathForItem(at: pos)!
let cell: CartCollectionViewCell = collection.cellForItem(at: indexPath) as! CartCollectionViewCell
if cell.qty != nil {
let value = String(Int(cell.qty.value))
var item = cart[indexPath.row]
item.value[3] = value
cart[indexPath.row] = item
}
}
func remove_from_cart(sender: UIButton){
let pos = sender.convert(CGPoint.zero, to: collection)
let indexPath = collection.indexPathForItem(at: pos)!
cart.remove(at: indexPath.row)
amount = 0.0
collection.reloadData()
}
after I scroll the collection view following error occurs:
"fatal error: unexpectedly found nil while unwrapping an Optional value"
let cell: CartCollectionViewCell = collection.cellForItem(at: indexPath) as! CartCollectionViewCell
this line is highlighted by Xcode.

How to get multiple buttons from a single tableViewcell?

I am making a quiz in a tableView that has 4 Buttons (options), I tagged them on a story board like 201,202,203,204 and got all of them successfully in tableView methods. But after adding targets to buttons, I am not able to get particular buttons in buttonClicked method.
func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 }
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return questions.count }
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
(cell.viewWithTag(100) as! UILabel).text = "Q : " + (questions[indexPath.row].objectForKey("MocQuestion")! as? String)!
(cell.viewWithTag(100) as! UILabel).font = themeFont
(cell.viewWithTag(101) as! UILabel).text = questions[indexPath.row].objectForKey("Op1")! as? String
(cell.viewWithTag(102) as! UILabel).text = questions[indexPath.row].objectForKey("Op2")! as? String
(cell.viewWithTag(103) as! UILabel).text = questions[indexPath.row].objectForKey("Op3")! as? String
(cell.viewWithTag(104) as! UILabel).text = questions[indexPath.row].objectForKey("Op4")! as? String
let btn1 = (cell.viewWithTag(201) as! UIButton)
let btn2 = (cell.viewWithTag(202) as! UIButton)
let btn3 = (cell.viewWithTag(203) as! UIButton)
let btn4 = (cell.viewWithTag(204) as! UIButton)
// btn1.tag = indexPath.row * 100 + 0
// btn1.tag = indexPath.row * 100 + 1
// btn1.tag = indexPath.row * 100 + 2
// btn1.tag = indexPath.row * 100 + 3
btn1.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
btn2.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
btn3.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
btn4.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
func buttonClicked(sender:UIButton)
{
let tag = sender.tag
print(tag)
}
If you want the indexPath to access the questions Array then you can try like this.
func buttonClicked(sender:UIButton) {
let center = sender.center
let point = sender.superview!.convertPoint(center, toView:self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(point)
//Now you have tag of button check for that
if (sender.tag == 201) {
print("Option A")
}
else if (sender.tag == 202) {
print("Option B")
}
else if (sender.tag == 203) {
print("Option C")
}
else {
print("Option D")
}
print(question[indexPath.row])
}
In swift 3 You can try bellow like
My table cell class
class Custom_Cell: UITableViewCell {
#IBOutlet weak var ButtonA: UIButton!
#IBOutlet weak var ButtonB: UIButton!
#IBOutlet weak var ButtonC: UIButton!
}
Set Tag in table view
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Custom_Cell;
cell.ButtonA.tag = indexPath.row;
cell.ButtonB.tag = indexPath.row;
cell.ButtonA.tag = indexPath.row;
//Add Action Methods to UIButtons
cell.ButtonA.addTarget(self, action: #selector(ButtonAAction), for: .touchUpInside)
cell.ButtonB.addTarget(self, action: #selector(ButtonBAction), for: .touchUpInside)
cell.ButtonA.addTarget(self, action: #selector(ButtonCAction), for: .touchUpInside)
return cell;
}
Button Action will look like ..
func ButtonAAction(_ sender: Any) {
//Get Button cell position.
let ButtonPosition = (sender as AnyObject).convert(CGPoint.zero, to: tableView)
let indexPath = tableView.indexPathForRow(at: ButtonPosition)
if indexPath != nil {
print("Cell indexPath: \(indexPath?.row)")
}
}
In order to get every ques separate button click event you can pass the unique ID as postfix or prefix e.g 20101 or 01201 of every ques as a tag of button instead of hard-coded. Then get the tag and extract ques id first now proceed for examination as per ques.

Resources