iOS Eureka: How to select first value as default after lazy get - ios

I have a list retrieved from REST API to Eureka's PushRow, but in case none is selected (creating a new object) I want first option to be selected by default after option list is retrieved.
However, PushRow only loads list after it's clicked on.
So is there a way to load PushRow lazy options together with it's section, or should I switch to other type of row (if it support's lazy)

You can use
$0.value // To set default value for PushRow()
Check that value is there before set to $0.value
Here what i used
<<< PushRow<String>(){
$0.tag = String(index)
$0.selectorTitle = checklistFieldNames[index] //
$0.options = ["YES", "NO"]
if question.count == 0{
$0.value = ""
}else {
$0.value = checklistFieldAnswers[0]
}
}.onPresent({ (from, to) in
to.dismissOnChange = false
to.dismissOnSelection = true
to.tableView?.backgroundColor = UIColor(displayP3Red: 244/255, green: 244/255, blue: 244/255, alpha: 1.0)
to.view.backgroundColor = UIColor(displayP3Red: 244/255, green: 244/255, blue: 244/255, alpha: 1.0)
to.selectableRowCellUpdate = { cell, row in
cell.textLabel?.font = UIFont(name: "DTLProkyonT", size: 15)
cell.textLabel?.textColor = UIColor.lightGray
cell.textLabel?.numberOfLines = 0
cell.textLabel?.backgroundColor = UIColor.clear
}
})

Related

How to change UIView "backgroundColor" and resize it appending text in UITextField (validation)? / Swift 5

Hello everyone!) Need some help!)
I have password validation text field and right now I'm setting UI. In text field I have only four rules. I created validation line which is UIView which has width - 348. The width and color of UIView must change every time if we add one rule to text field. If we have four rules, we must divide validation line by four: 348 / 4 = 87, and create four colors for it like red, orange, yellow and green.
How can I make the UIView available to update the width and color every time I add or subtract one rule in text field, like one lowercased character, digits, one uppercased character, ect...?)
Text field with four rules:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = validationTextField.text else { return true }
guard let textRange = Range(range, in: text) else { return true }
let updatedText = text.replacingCharacters(in: textRange, with: string)
//Minimum eight characters
if updatedText.count >= 8 {
eightCharsLablel.text = "⎷ minimum of 8 characters."
eightCharsLablel.textColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
textFieldValidLineView.frame.size.width = 0 + 87
} else {
eightCharsLablel.text = "– minimum of 8 characters."
eightCharsLablel.textColor = #colorLiteral(red: 0.2849253164, green: 0.1806431101, blue: 0.5, alpha: 1)
}
//Minimum one digit
if updatedText.range(of: #"\d+"#, options: .regularExpression) != nil {
oneDigitLablel.text = "⎷ minimum 1 digit."
oneDigitLablel.textColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
textFieldValidLineView.frame.size.width = 0 + 87
} else {
oneDigitLablel.text = "– minimum 1 digit."
oneDigitLablel.textColor = #colorLiteral(red: 0.2849253164, green: 0.1806431101, blue: 0.5, alpha: 1)
}
//Minimum one lowercased
if updatedText.range(of: #".*[a-z]+.*"#, options: .regularExpression) != nil {
oneLowercasedLablel.text = "⎷ minimum 1 lowercased."
oneLowercasedLablel.textColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
} else {
oneLowercasedLablel.text = "– minimum 1 lowercased."
oneLowercasedLablel.textColor = #colorLiteral(red: 0.2849253164, green: 0.1806431101, blue: 0.5, alpha: 1)
}
//Minimum one uppercased
if updatedText.range(of: #".*[A-Z]+.*"#, options: .regularExpression) != nil {
oneUppercasedLablel.text = "⎷ minimum 1 uppercased."
oneUppercasedLablel.textColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
} else {
oneUppercasedLablel.text = "– minimum 1 uppercased."
oneUppercasedLablel.textColor = #colorLiteral(red: 0.2849253164, green: 0.1806431101, blue: 0.5, alpha: 1)
}
//No whitespaces
if updatedText.range(of: #"\s+"#, options: .regularExpression) != nil {
return false
}
return true
}
Thanks for every answer!)
One way to do this that avoids any size calculations is to use a Horizontal UIStackView for your "ValidationLine".
If we set the stack view .distribution = .fillEqually, and then add a view for each "rule", the layout will happen automatically:
Then, to "grow and color" the "line" we can set the background colors of the arranged subviews based on how many rules have been "met":
Here's a complete example you can try out:
class ViewController: UIViewController, UITextFieldDelegate {
let ruleColors: [UIColor] = [
.red, .orange, .yellow, .green,
]
let validationTextField = UITextField()
let eightCharsLablel = UILabel()
let oneDigitLablel = UILabel()
let oneLowercasedLablel = UILabel()
let oneUppercasedLablel = UILabel()
// horizontal Stack View
let validationLineStackView: UIStackView = {
let v = UIStackView()
v.axis = .horizontal
v.distribution = .fillEqually
v.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
// add one view for each rule to the validationLineStackView
// we'll set the background colors when we satisfy rules
for _ in 0..<ruleColors.count {
let v = UIView()
v.backgroundColor = .clear
validationLineStackView.addArrangedSubview(v)
}
// put everything in a vertical stack view for this example
let stackView = UIStackView()
stackView.axis = .vertical
stackView.spacing = 8
stackView.addArrangedSubview(validationTextField)
stackView.addArrangedSubview(validationLineStackView)
stackView.addArrangedSubview(eightCharsLablel)
stackView.addArrangedSubview(oneDigitLablel)
stackView.addArrangedSubview(oneLowercasedLablel)
stackView.addArrangedSubview(oneUppercasedLablel)
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// stack view Top/Leading/Trailing with 20-points "padding"
stackView.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
stackView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
stackView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
// we'll use the intrinsic heights for the text field and all labels
// but we need to set the height of the validationLineStackView
validationLineStackView.heightAnchor.constraint(equalToConstant: 8.0),
])
// to make it easier to see the text field
validationTextField.borderStyle = .roundedRect
validationTextField.backgroundColor = .cyan
validationTextField.delegate = self
// initial update
updateRulesProgress("")
}
func updateRulesProgress(_ updatedText: String) {
var numRulesMet: Int = 0
//Minimum eight characters
if updatedText.count >= 8 {
eightCharsLablel.text = "⎷ minimum of 8 characters."
eightCharsLablel.textColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
// increment our "met" rules counter
numRulesMet += 1
} else {
eightCharsLablel.text = "– minimum of 8 characters."
eightCharsLablel.textColor = #colorLiteral(red: 0.2849253164, green: 0.1806431101, blue: 0.5, alpha: 1)
}
//Minimum one digit
if updatedText.range(of: #"\d+"#, options: .regularExpression) != nil {
oneDigitLablel.text = "⎷ minimum 1 digit."
oneDigitLablel.textColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
// increment our "met" rules counter
numRulesMet += 1
} else {
oneDigitLablel.text = "– minimum 1 digit."
oneDigitLablel.textColor = #colorLiteral(red: 0.2849253164, green: 0.1806431101, blue: 0.5, alpha: 1)
}
//Minimum one lowercased
if updatedText.range(of: #".*[a-z]+.*"#, options: .regularExpression) != nil {
oneLowercasedLablel.text = "⎷ minimum 1 lowercased."
oneLowercasedLablel.textColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
// increment our "met" rules counter
numRulesMet += 1
} else {
oneLowercasedLablel.text = "– minimum 1 lowercased."
oneLowercasedLablel.textColor = #colorLiteral(red: 0.2849253164, green: 0.1806431101, blue: 0.5, alpha: 1)
}
//Minimum one uppercased
if updatedText.range(of: #".*[A-Z]+.*"#, options: .regularExpression) != nil {
oneUppercasedLablel.text = "⎷ minimum 1 uppercased."
oneUppercasedLablel.textColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
// increment our "met" rules counter
numRulesMet += 1
} else {
oneUppercasedLablel.text = "– minimum 1 uppercased."
oneUppercasedLablel.textColor = #colorLiteral(red: 0.2849253164, green: 0.1806431101, blue: 0.5, alpha: 1)
}
// now update the background colors of the views in the validationLineStackView
for i in 0..<validationLineStackView.arrangedSubviews.count {
if i < numRulesMet {
validationLineStackView.arrangedSubviews[i].backgroundColor = ruleColors[numRulesMet - 1]
} else {
validationLineStackView.arrangedSubviews[i].backgroundColor = .clear
}
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = validationTextField.text else { return true }
guard let textRange = Range(range, in: text) else { return true }
let updatedText = text.replacingCharacters(in: textRange, with: string)
// make this the first IF case, since we'll return without allowing the
// text to change -- so no need to check anything else
//No whitespaces
if updatedText.range(of: #"\s+"#, options: .regularExpression) != nil {
return false
}
// move all the rule IFs to the updateRulesProgress function
updateRulesProgress(updatedText)
return true
}
}

Validate UITextField text letter by letter as it is entered

So I have a validation for my textfield, if the validation is true my button will be enabled and if the validation is false my button will be disable. The problem is the validation only runs after I click the done button in the keyboard.
I want the validation check letter by letter.
Here is my code:
func textFieldDidEndEditing(_ textField: UITextField) {
if (nomorTextField.text!.count >= 10) {
nextButton.isEnabled = true
nextButton.backgroundColor = #colorLiteral(red: 1, green: 0.4431372549, blue: 0.003921568627, alpha: 1)
if(nomorTextField.text!.count > 13) {
nextButton.isEnabled = false
nextButton.backgroundColor = #colorLiteral(red: 0.662745098, green: 0.662745098, blue: 0.662745098, alpha: 1)
}
else if emailTextFeild.text == "" {
nextButton.isEnabled = true
nextButton.backgroundColor = #colorLiteral(red: 1, green: 0.4431372549, blue: 0.003921568627, alpha: 1)
}
else if emailTextFeild.text?.isEmail == false {
nextButton.isEnabled = false
nextButton.backgroundColor = #colorLiteral(red: 0.662745098, green: 0.662745098, blue: 0.662745098, alpha: 1)
}
}
else {
nextButton.isEnabled = false
nextButton.backgroundColor = #colorLiteral(red: 0.662745098, green: 0.662745098, blue: 0.662745098, alpha: 1)
}
}
You can also connect it as an IBAction from storyboard (if you're using storyboards)
P.S. don't forget to change type to UITextField, and event to ValueChanged.
You should use a different delegate method -
textField(_:shouldChangeCharactersIn:replacementString:)
This method is called right before the characters are changed in the text field. You should always return true because in your case you are not looking to prevent text edits. However you do need to update the edited text field text with the new characters to make sure the count is correct.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Casting String as NSString to be able to replace characters using NSRange easily.
guard let text = textField.text as NSString? else { return true }
// Get the length of the final text
let finalTextCount = text.replacingCharacters(in: range, with: string).count
// Setup the text count for the field depending on which one was edited
let nomorTextFieldCount = textField == nomorTextField ? finalTextCount :
nomorTextField.text!.count
if nomorTextFieldCount >= 10 {
nextButton.isEnabled = true
nextButton.backgroundColor = #colorLiteral(red: 1, green: 0.4431372549, blue: 0.003921568627, alpha: 1)
if nomorTextFieldCount > 13 {
nextButton.isEnabled = false
nextButton.backgroundColor = #colorLiteral(red: 0.662745098, green: 0.662745098, blue: 0.662745098, alpha: 1)
}else if emailTextFeild.text == "" {
nextButton.isEnabled = true
nextButton.backgroundColor = #colorLiteral(red: 1, green: 0.4431372549, blue: 0.003921568627, alpha: 1)
}else if emailTextFeild.text?.isEmail == false{
nextButton.isEnabled = false
nextButton.backgroundColor = #colorLiteral(red: 0.662745098, green: 0.662745098, blue: 0.662745098, alpha: 1)
}
}else{
nextButton.isEnabled = false
nextButton.backgroundColor = #colorLiteral(red: 0.662745098, green: 0.662745098, blue: 0.662745098, alpha: 1)
}
return true
}

Swift ios how to change font , font color when tap and uptate , and some other properties in a segment control

I wanted to design tabs using segment control but the thing that i know regarding all its properties is just limited for now. the first image is my current one the 2nd image is what i want to achieve
What i really want to achieved is the segment control which has items all , pending , expired , finished. does anyone has an idea how to achieve distance between items in segments , also change the font color and style according to the design sample below. Thank You.
what i have so far.
let appearance = SMSegmentAppearance()
appearance.segmentOnSelectionColour = UIColor(red: 1, green: 0.8706, blue: 0.7608, alpha: 1.0)
appearance.segmentOffSelectionColour = UIColor(red: 1, green: 0.8706, blue: 0.7608, alpha: 1.0)
appearance.titleOnSelectionFont = UIFont.systemFont(ofSize: 25.0)
// segmentControlView.font = UIFont(name: "Avenir-Black", size: 12)
appearance.titleOffSelectionFont = UIFont.systemFont(ofSize: 25.0)
appearance.contentVerticalMargin = 10
/*
Init SMsegmentView
Set divider colour and width here if there is a need
*/
let segmentFrame = CGRect(x: self.margin, y: 5, width: self.segmentControlView.frame.size.width - self.margin*8, height: 50.0)
self.segmentView = SMSegmentView(frame: segmentFrame, dividerColour: UIColor(red: 1, green: 0.8706, blue: 0.7608, alpha: 1.0), dividerWidth: 1.0, segmentAppearance: appearance)
self.segmentView.backgroundColor = UIColor(red: 1, green: 0.8706, blue: 0.7608, alpha: 1.0)
self.segmentView.layer.cornerRadius = 5.0
self.segmentView.layer.borderColor = UIColor(red: 1, green: 0.8706, blue: 0.7608, alpha: 1.0).cgColor
self.segmentView.layer.borderWidth = 1.0
self.segmentView.addTarget(self, action: #selector(selectSegmentInSegmentView(segmentView:)), for: .valueChanged)
self.segmentView.addSegmentWithTitle("All", onSelectionImage: UIImage(named: ""), offSelectionImage: UIImage(named: ""))
self.segmentView.addSegmentWithTitle("Pending", onSelectionImage: UIImage(named: ""), offSelectionImage: UIImage(named: ""))
self.segmentView.addSegmentWithTitle("Finished", onSelectionImage: UIImage(named: ""), offSelectionImage: UIImage(named: ""))
self.segmentView.addSegmentWithTitle("Expired", onSelectionImage: UIImage(named: ""), offSelectionImage: UIImage(named: ""))
// var ownerNames = [String]()
//
// if fetchedToDoItems.count > 0 {
// for item in fetchedToDoItems {
// if item.houseNo == loggedInUserHouseNumber &&
// !ownerNames.contains(item.ownerName!) {
// ownerNames.append(item.ownerName!)
// }
// }
//
// for name in ownerNames {
// // Add segments
// self.segmentView.addSegmentWithTitle(name, onSelectionImage: UIImage(named: ""), offSelectionImage: UIImage(named: ""))
// }
//
// }
// Set segment with index 0 as selected by default
self.segmentView.selectedSegmentIndex = 0
self.segmentControlView.addSubview(self.segmentView)
As i have Seen the documentation:
You just need to change the Font style and size:
You can try :
Step:1 Print fonts
func printFonts() {
let fontFamilyNames = UIFont.familyNames
for familyName in fontFamilyNames {
print("------------------------------")
print("Font Family Name = [\(familyName)]")
let names = UIFont.fontNames(forFamilyName: familyName)
print("Font Names = [\(names)]")
}
}
Step :2 Set it to appearance:-
appearance.titleOnSelectionFont = UIFont(name: "TradeGothicLTStd-Cn18", size: 10.0)!
appearance.titleOffSelectionFont = UIFont(name: "TradeGothicLTStd-Cn18", size: 10.0)!
Hope this help!
Edit to set Selected to Black and Unselected to White
appearance.segmentOffSelectionColour = UIColor.white //UnSelected Colour
appearance.segmentOnSelectionColour = UIColor.black //Selected Colour

How can I hide 0 values on ios-chart?

I know that it is possible to hide y values when their values are equal to 0 on MPAndroidChart using a custom class for your value formatter (MPAndroidChart: Hide 0 value labels in a stacked bar chart).
Despite this, I am not able to create the same class on Swift 3.0 or get any other way to do this. I tried to "translate" the custom class from Java to Swift 3.0 without success (I can copy the code of what I have tried if you want but it is full of errors).
Is it possible to hide y values when they are equals to 0 on ios-chart library?
P.S: I am using Swift 3.0.
Thanks in advance!
I made it happen on a PieChart in one of my apps just like that :
...
let dataSet = PieChartDataSet(yVals: yVals, label: nil)
// This is where the magic happen
// You set a NSNumberFormatter with an empty zero Symbol
let noZeroFormatter = NumberFormatter()
noZeroFormatter.zeroSymbol = ""
dataSet.valueFormatter = ChartDefaultValueFormatter(formatter: noZeroFormatter)
let chartData = PieChartData(xVals: xVals, dataSet: dataSet)
...
if you want to add % in in your graph as well as hide/remove 0.0 values from graph :
used below lines of code for # Swift 3:-
func updateChartData() {
let chart = PieChartView(frame: mViewOutlet.frame)
// let chart = PieChartView(frame: CGRect(x: 122, y: 235 , width: self.mViewOutlet.frame.size.width, height: self.mViewOutlet.frame.size.height))
// 2. generate chart data entries
let track = ["Present","Leave", "EG/LC", "Halfday", "Absent", "Weeklyoff", "Holidays"]
// let money = [65, 13, 10, 2]
let money = mDaysArray
var entries = [PieChartDataEntry]()
for (index, value) in money.enumerated() {
print("index: \(index) \n value: \(value)")
let entry = PieChartDataEntry()
if value != 0 {
entry.y = Double(value)
}else{
}
entries.append(entry)
// entry.label = track[index] // if we want to remove name label
}
// 3. chart setup
let set = PieChartDataSet( values: entries, label: "Pie Chart")
// this is custom extension method. Download the code for more details.
//4. set chart color
let presentColor = UIColor(red: 80.0/255.0, green: 180.0/255.0, blue: 50.0/255.0, alpha: 1.0)
// let lateColor = UIColor(red: 241.0/255.0, green: 194.0/255.0, blue: 114.0/255.0, alpha: 1.0)
let leaveColor = UIColor(red: 203.0/255.0, green: 68.0/255.0, blue: 242.0/255.0, alpha: 1.0)
let egColor = UIColor(red: 95.0/255.0, green: 180.0/255.0, blue: 239.0/255.0, alpha: 1.0)
let halfdayColor = UIColor(red: 82.0/255.0, green: 64.0/255.0, blue: 152.0/255.0, alpha: 1.0)
let absentColor = UIColor(red: 242.0/255.0, green: 58.0/255.0, blue: 02.0/255.0, alpha: 1.0)
let weekOffColor = UIColor(red: 186.0/255.0, green: 221.0/255.0, blue: 79.0/255.0, alpha: 1.0)
let holidayColor = UIColor(red: 35.0/255.0, green: 215.0/255.0, blue: 179.0/255.0, alpha: 1.0)
let colors: [UIColor] = [presentColor,leaveColor,egColor,halfdayColor,absentColor,weekOffColor,holidayColor]
set.colors = colors
let data = PieChartData(dataSet: set)
let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.maximumFractionDigits = 2
formatter.multiplier = 1.0
formatter.percentSymbol = "%"
formatter.zeroSymbol = ""
data.setValueFormatter(DefaultValueFormatter(formatter: formatter))
chart.data = data
chart.noDataText = "No data available"
chart.usePercentValuesEnabled = true
// user interaction
chart.isUserInteractionEnabled = false
let d = Description()
// d.text = "iOSCharts.io"
chart.chartDescription = d
// chart.tintColor = UIColor.black
// chart.centerText = "Pie Chart"
chart.holeRadiusPercent = 0.2
chart.chartDescription?.enabled = false
chart.legend.enabled = false
chart.data?.notifyDataChanged()
chart.notifyDataSetChanged()
chart.setNeedsDisplay()
chart.animate(xAxisDuration: 1.3, yAxisDuration: 1.3)
chart.transparentCircleColor = UIColor.clear
// self.view.addSubview(chart)
self.mPieChartMainView.addSubview(chart)
}
let data = PieChartData(dataSet: set)
let pFormatter = NumberFormatter()
pFormatter.numberStyle = .none
pFormatter.zeroSymbol = "";
pFormatter.maximumFractionDigits = 1
pFormatter.multiplier = 1
pFormatter.percentSymbol = ""
data.setValueFormatter(DefaultValueFormatter(formatter: pFormatter))

Views from UITableView disappearing

I have a custom cell that is showing 14 different views. Depending on what data the cell is receiving it should show the views that are equal to the .count of some data, and the color should change depending on what data it is.
For instance:
If it is receiving three types of data, it should only show 3 views. Could be ice cream, candy, marshmellows. Then it would show three views, in orange (ice cream), blue (candy), green (marshmellows).
I got that working pretty well and I am excited about it. The problem is, if I have a cell showing three views and scroll down to a cell only containing 1 view (because the data was only one), then when I scroll up to the first cell again that should originally show three views, it is only showing 1, the first one..
I have an example:
My custom cell in storyboard is like this, the green and black boxes are the different views
This is what it looks like with 6 types of data:
When I then scroll down to a cell containing one view, the cell with 6 views will look like this afterwards:
Here is some relevant code:
Let me explain the code. In my database, every post has a category which is either 1 or 2. That is what the code is searching for, in update.category. If it is category 1, then it is just plain text. If it is category 2 ( or something else ) it should show the views, so I actually have to types of cells in my UITableViewController.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let update = updates[indexPath.row]
if update.category == 1 {
let cell:updateTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! updateTableViewCell
cell.nameButton.setTitle(update.addedByUser, forState: .Normal)
return cell
} else {
let cellSugar:newSugarTableViewCell = tableView.dequeueReusableCellWithIdentifier("CellSugar", forIndexPath: indexPath) as! newSugarTableViewCell
cellSugar.nameButton.setTitle(update.addedByUser, forState: .Normal)
let sugarArray = update.content.componentsSeparatedByString("--")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
cellSugar.sugarViewOne.layer.cornerRadius = cellSugar.sugarViewOne.frame.size.width/2
cellSugar.sugarViewOne.clipsToBounds = true
cellSugar.sugarViewOne.layer.borderColor = UIColor.whiteColor().CGColor
cellSugar.sugarViewOne.layer.borderWidth = 2.0
cellSugar.sugarViewTwo.layer.cornerRadius = cellSugar.sugarViewTwo.frame.size.width/2
cellSugar.sugarViewTwo.clipsToBounds = true
cellSugar.sugarViewTwo.layer.borderColor = UIColor.whiteColor().CGColor
cellSugar.sugarViewTwo.layer.borderWidth = 2.0
})
if sugarArray.count == 1 {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let seperateSugarArray = sugarArray[0].componentsSeparatedByString("#")
if seperateSugarArray[4] == "Candy" {
cellSugar.sugarViewOne.backgroundColor = UIColor(red: 97.0/255.0, green: 194.0/255.0, blue: 231.0/255.0, alpha: 1.0) // Blå
} else if seperateSugarArray[4] == "Ice cream" {
cellSugar.sugarViewOne.backgroundColor = UIColor(red: 35.0/255.0, green: 117.0/255.0, blue: 147.0/255.0, alpha: 1.0) // Mørke grå/blå
} else if seperateSugarArray[4] == "Marshmellows" {
cellSugar.sugarViewOne.backgroundColor = UIColor(red: 75.0/255.0, green: 212.0/255.0, blue: 159.0/255.0, alpha: 1.0) // Tyrkis
}
cellSugar.sugarViewTwo.hidden = true
cellSugar.sugarViewThree.hidden = true
cellSugar.sugarViewFour.hidden = true
cellSugar.sugarViewFive.hidden = true
cellSugar.sugarViewSix.hidden = true
cellSugar.sugarViewSeven.hidden = true
cellSugar.sugarViewEight.hidden = true
cellSugar.sugarViewNine.hidden = true
cellSugar.sugarViewTen.hidden = true
cellSugar.sugarViewEleven.hidden = true
cellSugar.sugarViewTwelve.hidden = true
cellSugar.sugarViewThirteen.hidden = true
cellSugar.sugarViewFourteen.hidden = true
})
} else if sugarArray.count == 2 {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let seperateSugarArray = sugarArray[0].componentsSeparatedByString("#")
let seperateSugarArrayTwo = sugarArray[1].componentsSeparatedByString("#")
if seperateSugarArray[4] == "Candy" {
cellSugar.sugarViewOne.backgroundColor = UIColor(red: 97.0/255.0, green: 194.0/255.0, blue: 231.0/255.0, alpha: 1.0) // Blå
} else if seperateSugarArray[4] == "Ice cream" {
cellSugar.sugarViewOne.backgroundColor = UIColor(red: 35.0/255.0, green: 117.0/255.0, blue: 147.0/255.0, alpha: 1.0) // Mørke grå/blå
} else if seperateSugarArray[4] == "Marshmellows" {
cellSugar.sugarViewOne.backgroundColor = UIColor(red: 75.0/255.0, green: 212.0/255.0, blue: 159.0/255.0, alpha: 1.0) // Tyrkis
}
if seperateSugarArray[4] == "Candy" {
cellSugar.sugarViewTwo.backgroundColor = UIColor(red: 97.0/255.0, green: 194.0/255.0, blue: 231.0/255.0, alpha: 1.0) // Blå
} else if seperateSugarArray[4] == "Ice cream" {
cellSugar.sugarViewTwo.backgroundColor = UIColor(red: 35.0/255.0, green: 117.0/255.0, blue: 147.0/255.0, alpha: 1.0) // Mørke grå/blå
} else if seperateSugarArray[4] == "Marshmellows" {
cellSugar.sugarViewTwo.backgroundColor = UIColor(red: 75.0/255.0, green: 212.0/255.0, blue: 159.0/255.0, alpha: 1.0) // Tyrkis
}
cellSugar.sugarViewThree.hidden = true
cellSugar.sugarViewFour.hidden = true
cellSugar.sugarViewFive.hidden = true
cellSugar.sugarViewSix.hidden = true
cellSugar.sugarViewSeven.hidden = true
cellSugar.sugarViewEight.hidden = true
cellSugar.sugarViewNine.hidden = true
cellSugar.sugarViewTen.hidden = true
cellSugar.sugarViewEleven.hidden = true
cellSugar.sugarViewTwelve.hidden = true
cellSugar.sugarViewThirteen.hidden = true
cellSugar.sugarViewFourteen.hidden = true
})
}
return cellSugar
}
}
I hope you understand and that you can help me, as it is pretty annoying :-)
You have to update all elements for each condition.
the cause of your issue: the table view is reusing the cells so if you have a cell showing 5 labels and after scrolling you have another one has a 3 and the other 2 is hidden, when you scroll up again you have to make them visible again a table view is using the one with 2 hidden labels.
In CellForRowAtIndexPath add the missing labels in each conditions
or in your custom UItableViewCell class add the method prepareForReuseand make all the labels visible.
UITableView reuse cells in a way that it takes one cell in its current state (with all its views configured) and return that cell for an other row, for which you need to again configure the cell as you need.
if update.category == 1 {
let cell:updateTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! updateTableViewCell
cell.nameButton.setTitle(update.addedByUser, forState: .Normal)
return cell
}
You need to configure your cell for a current row data before returning it.

Resources