Swift. Error updating UITextView in UITableViewCell - ios

I have a UITableView in which multiple cells are registered.
private lazy var table: UITableView = {
let table = UITableView(frame: .zero, style: .plain)
table.backgroundColor = .clear
table.separatorStyle = .none
table.dataSource = self.dataProvider
table.delegate = self.dataProvider
table.rowHeight = UITableView.automaticDimension
table.autoresizesSubviews = true
table.estimatedRowHeight = CreateContentLayout.cellHeight
table.register(CreateContentTextCell.classForCoder(), forCellReuseIdentifier: CreateContentTextCell.self.nameOfClass())
table.register(CCOutlinedTextAreaCell.classForCoder(), forCellReuseIdentifier: CCOutlinedTextAreaCell.self.nameOfClass())
table.register(CreateContentButtonCell.classForCoder(), forCellReuseIdentifier: CreateContentButtonCell.self.nameOfClass())
table.register(CreateContentPhotoCell.classForCoder(), forCellReuseIdentifier: CreateContentPhotoCell.self.nameOfClass())
table.register(CreateContentLableCell.classForCoder(), forCellReuseIdentifier: CreateContentLableCell.self.nameOfClass())
table.register(CreatContetnAttachmentsCell.classForCoder(), forCellReuseIdentifier: CreatContetnAttachmentsCell.self.nameOfClass())
table.contentInset = .zero
table.showsVerticalScrollIndicator = false
table.keyboardDismissMode = .onDrag
table.tableFooterView = UIView(frame: .zero)
return table
}()
One cell is for entering text, the other for attaching an image.
The cell for entering text contains a UITextView. When typing text the UITextView and UITableViewCell increase the height, everything works fine.
private lazy var textField: MDCOutlinedTextArea = {
let field = MDCOutlinedTextArea()
let title: String
field.minimumNumberOfVisibleRows = 1
field.maximumNumberOfVisibleRows = .infinity
field.textView.font = CreateContentLayout.lableAboutFont
field.setOutlineColor(Color.gray, for: .normal)
field.setOutlineColor(Color.blueGray, for: .editing)
field.setTextColor(.black, for: .normal)
field.setTextColor(.black, for: .editing)
field.setFloatingLabel(Color.blueGray, for: .normal)
field.setFloatingLabel(Color.blueGray, for: .editing)
switch self.data {
case let .subject(_, value, error), let .text(_, value, error), let .phone(value, error)/*, let .region(value, error)*/,
let .recipeInfo(value, error), let .ingredients(value, error), let .email(value, error), let .communications(value, error):
field.textView.backgroundColor = (value.isEmpty ? .clear : .white)
field.textView.text = value
default:
break
}
field.textView.delegate = self
return field
}()
func textViewDidChange(_ textView: UITextView) {
let size = textView.bounds.size
let newSize = textView.sizeThatFits(CGSize(width: size.width, height: CGFloat.greatestFiniteMagnitude))
let newHeight = (textField.sizeThatFits(CGSize(width: size.width, height: CGFloat.greatestFiniteMagnitude))).height
if size.height != newSize.height {
UIView.setAnimationsEnabled(false)
tableView?.beginUpdates()
self.textField.snp.updateConstraints {
$0.height.equalTo(newHeight)
}
tableView?.endUpdates()
UIView.setAnimationsEnabled(true)
}
self.scrollToRect(textView)
}
func setupUI() {
self.contentView.addSubview(textField)
self.textField.snp.makeConstraints {
$0.left.equalTo(BaseLayout.viewHorizontalPadding)
$0.right.equalTo(BaseLayout.viewHorizontalPadding.negated)
$0.top.equalTo(BaseLayout.viewHorizontalPadding)
$0.bottom.equalTo(BaseLayout.viewHorizontalPadding.negated).priority(.low)
}
NotificationCenter.default.addObserver(
self,
selector: #selector(textDidChange(_:)),
name: UITextView.textDidChangeNotification,
object: self.textField.textView
)
self.layoutIfNeeded()
let newSize = self.textField.sizeThatFits(CGSize(
width: UIScreen.main.bounds.width - BaseLayout.viewHorizontalPadding * 2,
height: CGFloat.greatestFiniteMagnitude
))
self.textField.snp.makeConstraints {
$0.height.equalTo(newSize.height)
}
However, when I add an image and the UITableView refreshes the cells, an extra area appears below.
More on video
error video
debug video

Related

Removing Elements from structure if they are blank so they are not displayed in UITableView

I have a simple gym workout App that consists of 2 view controllers (vc1 and vc2).
Users put some information into VC2, this is then this is passed to and displayed in VC1.
VC1 is a UITableView. The information in VC2 is stored in a struct and passed to VC1 via protocol delegate method.
The user inputs data in VC2 to fill the struct. Then VC1 populates itself based on the struct.
VC1 is an extendible UITableView. Users put in the title of the workout and then when the row is clicked the users can see the exercises that they entered along with their sets and reps.
my plan is to have 10 exercises sections that the users can enter.
My problem is that if the user doesn't want a workout to consist of 10 exercises, say they want the workout to consist of only 3 exercisers. So they will fill in the fields for 3 exercises only. I am left with 3 cells in the UITableView that are populated with information and 7 that are occupied by black strings.
How can I get rid of the 7 blank exercises so they will not show up in the UITableView? In this code below I have only added one exercise element not 10 yet. I just want to solve this issue first while the code isn't too big.
VC1 is called ContactsController this is the UITableView:
import Foundation
import UIKit
private let reuseidentifier = "Cell"
struct cellData {
var opened = Bool()
var title = String()
var sectionData = [String]()
}
//here
struct Contact {
var fullname: String
var excerciseOne: String
var excerciseOneReps: String
var excerciseOneSets: String
}
class ContactController: UITableViewController {
//new
var tableViewData = [cellData]()
var contacts = [Contact]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.title = "Workouts"
// self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(handleAddContact))
view.backgroundColor = .white
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseidentifier)
}
#IBAction func handleAddContact(_ sender: Any) {
let controller = AddContactController()
controller.delegate = self
self.present(UINavigationController(rootViewController: controller), animated: true, completion: nil)
}
//UITABLEVIEW
//all new
override func numberOfSections(in tableView: UITableView) -> Int {
//new
return tableViewData.count
}
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
//old needed return contacts.count
//new
if tableViewData[section].opened == true {
return tableViewData[section].sectionData.count + 1
}else {
return 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//old needed let cell = tableView.dequeueReusableCell(withIdentifier: reuseidentifier, for: indexPath)
// cell.textLabel?.text = contacts[indexPath.row].fullname
// return cell
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseidentifier, for: indexPath)
cell.textLabel?.text = tableViewData[indexPath.section].title
return cell
}else {
//use a different cell identifier if needed
let cell = tableView.dequeueReusableCell(withIdentifier: reuseidentifier, for: indexPath)
// cell.textLabel?.text = tableViewData[indexPath.section].sectionData[indexPath.row]
cell.textLabel?.text = tableViewData[indexPath.section].sectionData[indexPath.row - 1]
return cell
}
}
//did select row new
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableViewData[indexPath.section].opened == true {
tableViewData[indexPath.section].opened = false
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .none) //play around with animation
}else {
tableViewData[indexPath.section].opened = true
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .none) //play around with animation
}
}
}
//this is an extention to addContactController. this is what happens whent he done button is clicked in addcontactcontroller
extension ContactController: AddContactDelegate {
func addContact(contact: Contact) {
self.dismiss(animated: true) {
self.contacts.append(contact)
self.tableViewData.append(cellData.init(opened: false, title: contact.fullname, sectionData: [contact.excerciseOne + " Reps: " + contact.excerciseOneReps + " Sets: " + contact.excerciseOneSets, "cell2", "cell3"]))
self.tableView.reloadData()
}
}
}
The Following is my VC2 where the user inputs the data to create a workout and its associated exercises:
import Foundation
import UIKit
//here
protocol AddContactDelegate {
func addContact(contact: Contact)
}
class AddContactController: UIViewController {
//delegate
var delegate: AddContactDelegate?
//Title TextField
let titleTextField: UITextField = {
let tf = UITextField()
tf.placeholder = "What you you like to call your workout?"
tf.textAlignment = .center
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
//Exercise 1 title TextField
let excercise1TextField: UITextField = {
let ex1 = UITextField()
ex1.placeholder = "What excercise are you doing?"
ex1.textAlignment = .center
ex1.translatesAutoresizingMaskIntoConstraints = false
return ex1
}()
//Exercise 1 title TextField
let excercise1RepsTextField: UITextField = {
let ex1Reps = UITextField()
ex1Reps.placeholder = "Reps"
ex1Reps.textAlignment = .center
ex1Reps.translatesAutoresizingMaskIntoConstraints = false
return ex1Reps
}()
//Exercise 1 title TextField
let excercise1SetsTextField: UITextField = {
let ex1Sets = UITextField()
ex1Sets.placeholder = "Sets"
ex1Sets.textAlignment = .center
ex1Sets.translatesAutoresizingMaskIntoConstraints = false
return ex1Sets
}()
override func viewDidLoad() {
super.viewDidLoad()
//making scroll view
let screensize: CGRect = UIScreen.main.bounds
let screenWidth = screensize.width
let screenHeight = screensize.height
var scrollView: UIScrollView!
scrollView = UIScrollView(frame: CGRect(x: 0, y: 120, width: screenWidth, height: screenHeight))
scrollView.contentSize = CGSize(width: screenWidth, height: 2000)
view.addSubview(scrollView)
//setting up how view looks-----
view.backgroundColor = .white
//top buttons
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(handleDone))
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(handleCancel))
//view elements in scrollview
//Workout Title label
let workoutTitleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 25))
workoutTitleLabel.center = CGPoint(x: view.frame.width / 2 , y: view.frame.height / 20)
workoutTitleLabel.textAlignment = .center
workoutTitleLabel.text = "Workout Title"
workoutTitleLabel.font = UIFont.boldSystemFont(ofSize: 20)
scrollView.addSubview(workoutTitleLabel)
//workout title textfield
scrollView.addSubview(titleTextField)
titleTextField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleTextField.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
// textField.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor),
titleTextField.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor ,constant: -350),
titleTextField.widthAnchor.constraint(equalToConstant: view.frame.width - 64)
])
titleTextField.becomeFirstResponder()
//excercise 1 the locked in title Label
let excersice1label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
excersice1label.center = CGPoint(x: view.frame.width / 2 , y: view.frame.height / 5)
excersice1label.textAlignment = .center
excersice1label.text = "Excercise 1"
excersice1label.font = UIFont.boldSystemFont(ofSize: 20)
scrollView.addSubview(excersice1label)
//excercise 1 title textField
scrollView.addSubview(excercise1TextField)
excercise1TextField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
excercise1TextField.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
// textField.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor),
excercise1TextField.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor ,constant: -220),
excercise1TextField.widthAnchor.constraint(equalToConstant: view.frame.width - 64)
])
excercise1TextField.becomeFirstResponder()
//excercise 1 Reps textField
scrollView.addSubview(excercise1RepsTextField)
excercise1RepsTextField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
excercise1RepsTextField.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
// textField.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor),
excercise1RepsTextField.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor ,constant: -190),
excercise1RepsTextField.widthAnchor.constraint(equalToConstant: view.frame.width - 64)
])
excercise1RepsTextField.becomeFirstResponder()
//excercise 1 Sets textField
scrollView.addSubview(excercise1SetsTextField)
excercise1SetsTextField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
excercise1SetsTextField.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
// textField.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor),
excercise1SetsTextField.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor ,constant: -160),
excercise1SetsTextField.widthAnchor.constraint(equalToConstant: view.frame.width - 64)
])
excercise1SetsTextField.becomeFirstResponder()
}
//done button
#objc func handleDone(){
print("done")
//setting the uitextfields to the the contact
guard let fullname = titleTextField.text, titleTextField.hasText else {
print("handle error here")
return
}
/* guard might be needed if a certain element is left empty
guard let excerciseOne = excercise1TextField.text, excercise1TextField.hasText else {
print("handle error here")
let excerciseOne = "empty"
return
}
*/
//setting the user input elements to to the contact so it can be passed to vc1 and presented
let excerciseOne = excercise1TextField.text
let excerciseOneReps = excercise1RepsTextField.text
let excerciseOneSets = excercise1SetsTextField.text
let contact = Contact(fullname: fullname, excerciseOne: excerciseOne!, excerciseOneReps: excerciseOneReps!, excerciseOneSets: excerciseOneSets!)
delegate?.addContact(contact: contact)
print(contact.fullname)
}
//cancel button
#objc func handleCancel(){
self.dismiss(animated: true, completion: nil )
}
}

There is change add to atop duplicate header, but there is a stretch effect?

enter image description hereThere is a stretch effect.But the additional header is duplicated , only without data.Can anyone correct my code that I wrote extra or incorrectly called the header?.I have custom Header xib. link tutorial https://mobikul.com/table-view-stretch-header-parallax-animation-in-swift/
My code:
var headerView: CustomSoccerHeaderView? = {
return Bundle.main.loadNibNamed("CustomSoccerHeaderView", owner: nil, options: nil)!.first as! CustomSoccerHeaderView
}()
override func viewDidLoad() {
super.viewDidLoad()
let backButton = UIBarButtonItem()
backButton.title = ""
self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
// self.navigationItem.rightBarButtonItem = barButton
// self.navigationItem.rightBarButtonItem?.tintColor = UIColor.universalColorYellow
let yourBackImage = UIImage(named: "backItem")
self.navigationController?.navigationBar.backIndicatorImage = yourBackImage
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = yourBackImage
self.navigationController?.navigationItem.leftItemsSupplementBackButton = true
self.navigationController?.navigationBar.tintColor = UIColor.universalColorYellow
//title = detailSoccer.detailTitleS
let nib: UINib = UINib(nibName: "CustomSoccerHeaderView", bundle: nil)
tableView.register(nib, forHeaderFooterViewReuseIdentifier: "CustomSoccerHeaderView")
tableView.tableFooterView = UIView(frame: .zero)
tableView.estimatedRowHeight = 280
headerView?.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 350)
tableView.tableHeaderView = headerView
tableView.tableHeaderView = nil
tableView.contentInset = UIEdgeInsets(top: 350, left: 0, bottom: 0, right: 0)
tableView.addSubview(headerView!)
tableView.separatorStyle = .none
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName:"FootTableViewCell",bundle:nil), forCellReuseIdentifier: "cellSoc")
self.view.addSubview(tableView)
tableView.rowHeight = UITableView.automaticDimension
tableView.reloadData()
loadMatchSoccer()
tableView.rowHeight = UITableView.automaticDimension
}
That's going to stretch the effect:
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
self.tableView.reloadData()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if headerView != nil {
let yPos: CGFloat = -scrollView.contentOffset.y
if yPos > 0 {
var imgRect: CGRect? = headerView?.frame
imgRect?.origin.y = scrollView.contentOffset.y
imgRect?.size.height = 350 + yPos - 350
headerView?.frame = imgRect!
self.tableView.sectionHeaderHeight = (imgRect?.size.height)!
}
}
}
This is the code for the header section of my file xib class.I think I make a mistake in inheriting the header or loading addsubview.Maybe someone more experienced can tweak my code.I would appreciate that.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomSoccerHeaderView") as! CustomSoccerHeaderView
header.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 350)
header.clickBravisso = detailSoccer
header.nameHeader.text = detailSoccer.matchS
header.countBravo.text = ""
// header.bravoBtn.addTarget(CustomSoccerHeaderView(), action: #selector(CustomSoccerHeaderView.likeBtn(_:)), for: UIControlEvents.touchUpInside)
detailSoccer.imagePrS.getDataInBackground { (data, error) in
header.imageHeader.image = error == nil ? UIImage(data: data!) : nil
}
return header
}

TextField returning Nil

I have custom UITextField in the UICollectionView, the textfield returns null always even if I pass some value from it , and the app crashes on the button click
Code:
func accountCollectionView(_ collectionView: UICollectionView?, cellForItemAt indexPath: IndexPath?) -> UICollectionViewCell?
{
let cell : RBLoginCell = collectionView!.dequeueReusableCell(withReuseIdentifier: "RBLoginCell", for: indexPath!) as! RBLoginCell
cell.backgroundColor = UIColor.clear
switch indexPath!.row {
case 0:
let txtFldUserId = cell.txtFld
txtFldUserId?.delegate = self
txtFldUserId?.placeholder = "Email Address"
txtFldUserId?.tag = 1
txtFldUserId?.keyboardType = .emailAddress
txtFldUserId?.returnKeyType = .next
txtFldUserId?.isSecureTextEntry = false
break
case 1:
let txtFldPassword = cell.txtFld
txtFldPassword?.delegate = self
txtFldPassword?.placeholder = "Password"
txtFldPassword?.tag = 2
txtFldPassword?.returnKeyType = .done
txtFldPassword?.isSecureTextEntry = true
break
default:
break
}
cell.setNeedsLayout()
return cell
}
on this method the app crashes while checking for the charcter count
func loginAction(sender:UIButton!)
{
if (txtFldUserId?.text?.characters.count)! > 0 {
if (txtFldPassword?.text?.characters.count)! > 0 {
user?.emailAddress = txtFldUserId?.text
user?.password = txtFldPassword?.text
postLoginRequest(user)
Custom cell class
class RBLoginCell : RBParentCell {
var txtFld : CustomTextField?
var separator : UIView?
override init(frame: CGRect) {
super.init(frame: frame)
txtFld = getTextField()
separator = getImageView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func getLabel() -> UILabel? {
let _lblInfo = UILabel(frame: CGRect.zero)
_lblInfo.backgroundColor = UIColor.clear
_lblInfo.textAlignment = .left
_lblInfo.textColor = UIColor.white
_lblInfo.numberOfLines = 0
addSubview(_lblInfo)
return _lblInfo
}
func getTextField(_ frame: CGRect) -> CustomTextField? {
let textField = CustomTextField(frame: frame)
textField.borderStyle = .none
textField.placeholder = ""
textField.backgroundColor = UIColor.clear
textField.autocorrectionType = .no
// no auto correction support
textField.keyboardType = .default
// use the default type input method (entire keyboard)
textField.returnKeyType = .next
textField.enablesReturnKeyAutomatically = false
textField.clearButtonMode = .never
textField.text = ""
textField.contentVerticalAlignment = .center
textField.autocapitalizationType = .none
//textField.frame = CGRectMake(X, Y,Width,Height);
textField.alpha = 1.0
textField.isUserInteractionEnabled = true
let lblleft: UILabel? = getLabel()
lblleft?.frame = CGRect(x: 0, y: 20, width: self.frame.size.width, height: self.frame.size.height)
lblleft?.backgroundColor = UIColor.clear
lblleft?.text = "\n+91"
lblleft?.font = UIFont(name: Constants.HelveticaNeue, size: 14)//FONT_HelveticaNeue(14.0)
lblleft?.textColor = UIColor(hexString: "555555")
textField.leftView = lblleft
textField.leftViewMode = .never
addSubview(textField)
return textField
}
override func getImageView() -> UIImageView? {
let imageView = UIImageView(frame: CGRect.zero)
imageView.backgroundColor = UIColor.lightGray
addSubview(imageView)
return imageView
}
override func layoutSubviews() {
super.layoutSubviews()
txtFld?.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height-1)
separator?.frame = CGRect(x: 0, y: (txtFld?.frame.size.height)!, width: frame.size.width, height: 1)
}
You have initialised
let txtFldUserId = cell.txtFld
and
let txtFldPassword = cell.txtFld
in your cellForItemAt method, how can you access it in loginAction method then?
If you have initialised txtFldUserId and txtFldPassword in your view controller, then remove let from the cellForItemAt method like
txtFldUserId = cell.txtFld
txtFldPassword = cell.txtFld
[I am assuming you have initialised in your viewController
var txtFldUserId: UITextField?
var txtFldPassword: UITextField?
because you are not getting compiler error in your loginAction method ]

UITableView with custom cells lags while scrolling

My problem is that UITableView lags quite a lot while scrolling.
This is what I am trying to achieve
Starting from the top I have a simple section header with only one checkbox and one UILabel. Under this header, you can see a custom cell with only one UILabel aligned to the center. This custom cell works like another header for the data that would be shown below (Basically a 3D array). Under these "headers" are custom cells that contain one multiline UILabel and under this label is a container for a variable amount of lines containing a checkbox and an UILabel. On the right side of the cell is also a button (blue/white arrow).
So this means the content is shown like this:
Section header (containing day and date)
Custom UITableViewCell = header (containing some header information)
Custom UITableViewCell (containing data to be shown)
Here is my code:
cellForRowAt:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let (isHeader, headerNumber, semiResult) = checkIfIsHeader(section: indexPath.section, row: indexPath.row)
let row = indexPath.row
if isHeader {
let chod = objednavkaDny[indexPath.section].chody[headerNumber+1]
let cell = tableView.dequeueReusableCell(withIdentifier: cellHeaderReuseIdentifier, for: indexPath) as! ObjednavkyHeaderTableViewCell
cell.titleLabel.text = chod.popisPoradiJidla
cell.selectionStyle = .none
return cell
}else{
let chod = objednavkaDny[indexPath.section].chody[headerNumber]
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! ObjednavkyTableViewCell
cell.updateData(objednavka: chod.objednavky[row-semiResult], canSetAmount: self.typDialogu == 3)
return cell
}
}
checkIfIsHeader:
func checkIfIsHeader(section: Int, row: Int) -> (Bool, Int, Int){
if let cachedResult = checkIfHeaderCache[section]?[row] {
return (cachedResult[0] == 1, cachedResult[1], cachedResult[2])
}
var isHeader = false
var semiResult = 0
var headerNumber = -1
for (index, chod) in objednavkaDny[section].chody.enumerated() {
let sum = chod.objednavky.count
if row == semiResult {
isHeader = true
break
}else if row < semiResult {
semiResult -= objednavkaDny[section].chody[index-1].objednavky.count
break
}else {
headerNumber += 1
semiResult += 1
if index != objednavkaDny[section].chody.count - 1 {
semiResult += sum
}
}
}
checkIfHeaderCache[section] = [Int:[Int]]()
checkIfHeaderCache[section]![row] = [isHeader ? 1 : 0, headerNumber, semiResult]
return (isHeader, headerNumber, semiResult)
}
and the main cell that shows the data:
class ObjednavkyTableViewCell: UITableViewCell {
lazy var numberTextField: ObjednavkyTextField = {
let textField = ObjednavkyTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
let mealLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = .black
label.textAlignment = .left
label.font = UIFont(name: ".SFUIText", size: 15)
label.numberOfLines = 0
label.backgroundColor = .white
label.isOpaque = true
return label
}()
lazy var detailsButton: UIButton = {
let button = UIButton(type: .custom)
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "arrow-right")?.withRenderingMode(.alwaysTemplate), for: .normal)
button.imageView?.tintColor = UIColor.custom.blue.classicBlue
button.imageView?.contentMode = .scaleAspectFit
button.contentHorizontalAlignment = .right
button.imageEdgeInsets = UIEdgeInsetsMake(10, 0, 10, 0)
button.addTarget(self, action: #selector(detailsButtonPressed), for: .touchUpInside)
button.backgroundColor = .white
button.isOpaque = true
return button
}()
let pricesContainerView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white
view.isOpaque = true
return view
}()
var canSetAmount = false {
didSet {
canSetAmount ? showNumberTextField() : hideNumberTextField()
}
}
var shouldShowPrices = false {
didSet {
shouldShowPrices ? showPricesContainerView() : hidePricesContainerView()
}
}
var pricesContainerHeight: CGFloat = 0
private let priceViewHeight: CGFloat = 30
var mealLabelLeadingConstraint: NSLayoutConstraint?
var mealLabelBottomConstraint: NSLayoutConstraint?
var pricesContainerViewHeightConstraint: NSLayoutConstraint?
var pricesContainerViewBottomConstraint: NSLayoutConstraint?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#objc func detailsButtonPressed() {
}
func updateData(objednavka: Objednavka, canSetAmount: Bool) {
self.canSetAmount = canSetAmount
if let popisJidla = objednavka.popisJidla, popisJidla != "", popisJidla != " " {
self.mealLabel.text = popisJidla
}else{
self.mealLabel.text = objednavka.nazevJidelnicku
}
if objednavka.objects.count > 1 {
shouldShowPrices = true
setPricesStackView(with: objednavka.objects)
checkIfSelected(objects: objednavka.objects)
}else{
shouldShowPrices = false
self.numberTextField.text = String(objednavka.objects[0].pocet)
//setSelected(objednavka.objects[0].pocet > 0, animated: false)
objednavka.objects[0].pocet > 0 ? setSelectedStyle() : setDeselectedStyle()
}
}
//---------------
func checkIfSelected(objects: [ObjednavkaObject]) {
var didChangeSelection = false
for object in objects { // Checks wether cell should be selected or not
if object.pocet > 0 {
setSelected(true, animated: false)
setSelectedStyle()
didChangeSelection = true
break
}
}
if !didChangeSelection {
setSelected(false, animated: false)
setDeselectedStyle()
}
}
//--------------
func showNumberTextField() {
numberTextField.isHidden = false
mealLabelLeadingConstraint?.isActive = false
mealLabelLeadingConstraint = mealLabel.leadingAnchor.constraint(equalTo: numberTextField.trailingAnchor, constant: 10)
mealLabelLeadingConstraint?.isActive = true
}
func hideNumberTextField() {
numberTextField.isHidden = true
mealLabelLeadingConstraint?.isActive = false
mealLabelLeadingConstraint = mealLabel.leadingAnchor.constraint(equalTo: readableContentGuide.leadingAnchor, constant: 0)
mealLabelLeadingConstraint?.isActive = true
}
func showPricesContainerView() {
hideNumberTextField()
pricesContainerView.isHidden = false
mealLabelBottomConstraint?.isActive = false
pricesContainerViewBottomConstraint?.isActive = true
}
func hidePricesContainerView() {
pricesContainerView.isHidden = true
pricesContainerViewBottomConstraint?.isActive = false
mealLabelBottomConstraint?.isActive = true
}
//--------------
func setSelectedStyle() {
self.backgroundColor = UIColor.custom.blue.classicBlue
mealLabel.textColor = .white
mealLabel.backgroundColor = UIColor.custom.blue.classicBlue
for subview in pricesContainerView.subviews where subview is ObjednavkyPriceView {
let priceView = (subview as! ObjednavkyPriceView)
priceView.titleLabel.textColor = .white
priceView.checkBox.backgroundColor = UIColor.custom.blue.classicBlue
priceView.titleLabel.backgroundColor = UIColor.custom.blue.classicBlue
priceView.backgroundColor = UIColor.custom.blue.classicBlue
}
pricesContainerView.backgroundColor = UIColor.custom.blue.classicBlue
detailsButton.imageView?.tintColor = .white
detailsButton.backgroundColor = UIColor.custom.blue.classicBlue
}
func setDeselectedStyle() {
self.backgroundColor = .white
mealLabel.textColor = .black
mealLabel.backgroundColor = .white
for subview in pricesContainerView.subviews where subview is ObjednavkyPriceView {
let priceView = (subview as! ObjednavkyPriceView)
priceView.titleLabel.textColor = .black
priceView.checkBox.backgroundColor = .white
priceView.titleLabel.backgroundColor = .white
priceView.backgroundColor = .white
}
pricesContainerView.backgroundColor = .white
detailsButton.imageView?.tintColor = UIColor.custom.blue.classicBlue
detailsButton.backgroundColor = .white
}
//-----------------
func setPricesStackView(with objects: [ObjednavkaObject]) {
let subviews = pricesContainerView.subviews
var subviewsToDelete = subviews.count
for (index, object) in objects.enumerated() {
subviewsToDelete -= 1
if subviews.count - 1 >= index {
let priceView = subviews[index] as! ObjednavkyPriceView
priceView.titleLabel.text = object.popisProduktu // + " " + NSNumber(value: object.cena).getFormattedString(currencySymbol: "Kč") // TODO: currencySymbol
priceView.canSetAmount = canSetAmount
priceView.count = object.pocet
priceView.canOrder = (object.nelzeObj == nil || object.nelzeObj == "")
}else {
let priceView = ObjednavkyPriceView(frame: CGRect(x: 0, y: CGFloat(index) * priceViewHeight + CGFloat(index * 5), width: pricesContainerView.frame.width, height: priceViewHeight))
pricesContainerView.addSubview(priceView)
priceView.titleLabel.text = object.popisProduktu // + " " + NSNumber(value: object.cena).getFormattedString(currencySymbol: "Kč") // TODO: currencySymbol
priceView.numberTextField.delegate = self
priceView.canSetAmount = canSetAmount
priceView.canOrder = (object.nelzeObj == nil || object.nelzeObj == "")
priceView.count = object.pocet
pricesContainerHeight += ((index == 0) ? 30 : 35)
}
}
if subviewsToDelete > 0 { // Deletes unwanted subviews
for _ in 0..<subviewsToDelete {
pricesContainerView.subviews.last?.removeFromSuperview()
pricesContainerHeight -= pricesContainerHeight + 5
}
}
if pricesContainerHeight < 0 {
pricesContainerHeight = 0
}
pricesContainerViewHeightConstraint?.constant = pricesContainerHeight
}
func setupView() {
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
self.backgroundColor = .white
contentView.addSubview(numberTextField)
contentView.addSubview(mealLabel)
contentView.addSubview(detailsButton)
contentView.addSubview(pricesContainerView)
setupConstraints()
}
func setupConstraints() {
numberTextField.anchor(leading: readableContentGuide.leadingAnchor, size: CGSize(width: 30, height: 30))
numberTextField.centerYAnchor.constraint(equalTo: mealLabel.centerYAnchor).isActive = true
detailsButton.anchor(trailing: readableContentGuide.trailingAnchor, size: CGSize(width: 30, height: 30))
detailsButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
mealLabel.anchor(top: contentView.topAnchor, trailing: detailsButton.leadingAnchor, padding: .init(top: 10, left: 0, bottom: 0, right: -10))
mealLabelBottomConstraint = mealLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10)
mealLabelBottomConstraint?.priority = UILayoutPriority(rawValue: 999)
pricesContainerView.anchor(top: mealLabel.bottomAnchor, leading: readableContentGuide.leadingAnchor, trailing: detailsButton.leadingAnchor, padding: .init(top: 10, left: 0, bottom: 0, right: -10))
pricesContainerViewBottomConstraint = pricesContainerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10)
pricesContainerViewBottomConstraint?.priority = UILayoutPriority(rawValue: 999)
pricesContainerViewHeightConstraint = pricesContainerView.heightAnchor.constraint(equalToConstant: 0)
pricesContainerViewHeightConstraint?.priority = UILayoutPriority(rawValue: 999)
pricesContainerViewHeightConstraint?.isActive = true
}
}
To conclude how it is done:
tableView.rowHeight is set to UITableViewAutomaticDymension
inside cellForRowAt I get the data from an array and give it to the
cell
all the cells are set up in code using constraints
all the views have set isOpaque = true
heights of the cells are cached
cells are set to rasterize
I also noticed that it lags at certain scroll levels and that sometimes it works just fine and sometimes it lags a lot.
Despite all of the optimization I have done, the tableView still lags while scrolling.
Here is a screenshot from Instruments
Any tip how to improve the scrolling performance is highly appreciated!
(I might have forgotten to include some code/information so feel free to ask me in the comments.)
I can't tell you where the lag happens exactly but when we are talking about lagging during scrolling, it's related to your cellForRowAt delegate method. What happends is that too many things are going on within this method and it's called for every cells that are displaying & going to display. I see that your are trying to cache the result by checkIfHeaderCache but still, there is a for loop at the very beginning to determine header cell.
Suggestions:
I don't know where you get data (objednavkaDny) from but right after you get the data, do a full loop through and determin cell type one by one, and save the result some where base on your design. During this loading time, you can show some loading message on the screen. Then, within the cellForRow method, you should be just simply using things like
if (isHeader) {
render header cell
} else {
render other cell
}
Bottom line:
cellForRow method is not designed to handle heavy calculations, and it will slow down the scrolling if you do so. This method is for assigning values to the cached table view cell only and that's the only thing it is good at.

How to make Horizontal scrollView and some buttons in it (programming)

sorry,I have a problem.I don't use storyBoard.
I want to make a view like this.
photo by terenceLuffy/AppStoreStyleHorizontalScrollView
but I try to do this.
Finlly,scrollView just show last button like this.
This is code:
var scView:UIScrollView = UIScrollView()
var buttonPadding:CGFloat = 10
var xOffset:CGFloat = 10
scView.backgroundColor = UIColor.blue
scView.translatesAutoresizingMaskIntoConstraints = false
func viewDidLoad() {
for i in 0 ... 10 {
let button = UIButton()
button.tag = i
button.backgroundColor = UIColor.darkGray
button.setTitle("\(i)", for: .normal)
button.addTarget(self, action: #selector(btnTouch), for: UIControlEvents.touchUpInside)
button.frame = CGRect(x: xOffset, y: CGFloat(buttonPadding), width: 70, height: 30)
xOffset = xOffset + CGFloat(buttonPadding) + button.frame.size.width
scView.addSubview(button)
}
scView.contentSize = CGSize(width: xOffset, height: scView.frame.height)
}
please help me.
Thanks all!
There are two ways of achieving it :) One the hard way using scrollView and calculating offset and setting views programmatically on ScrollView as subView else use CollectionView
Step 1:
Add a UICollectionView to storyboard, set the height of collectionView to match your requirement :)
Step 2
Create a cell, size of which depends on your requirement. I have created a cell with background colour orange/pink. Added a label on it to show your number.
Step 3:
Set the reusable cell identifier to the cell and set its class as well :)
Step 4 :
Set collectionView scroll direction to horizontal :)
Step 5:
Now implement collectionView delegates and data source methods :)
extension ViewController : UICollectionViewDataSource,UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! MyCollectionViewCell
cell.myLabel.text = "ABCD"
return cell;
}
}
Thats all :)
Final O/P
Look at collectionView with cell ABCD :D
Additional Info
If you are dragging a collectionView on UIViewController, you might see that the collectionView leaves a gap at the top which you can solve by unchecking Adjust ScrollView Insets of ViewController :)
I have tried your code and changed it a bit. It works as expected, unless you have something other going on:
var scView:UIScrollView!
let buttonPadding:CGFloat = 10
var xOffset:CGFloat = 10
override func viewDidLoad() {
super.viewDidLoad()
scView = UIScrollView(frame: CGRect(x: 0, y: 120, width: view.bounds.width, height: 50))
view.addSubview(scView)
scView.backgroundColor = UIColor.blue
scView.translatesAutoresizingMaskIntoConstraints = false
for i in 0 ... 10 {
let button = UIButton()
button.tag = i
button.backgroundColor = UIColor.darkGray
button.setTitle("\(i)", for: .normal)
//button.addTarget(self, action: #selector(btnTouch), for: UIControlEvents.touchUpInside)
button.frame = CGRect(x: xOffset, y: CGFloat(buttonPadding), width: 70, height: 30)
xOffset = xOffset + CGFloat(buttonPadding) + button.frame.size.width
scView.addSubview(button)
}
scView.contentSize = CGSize(width: xOffset, height: scView.frame.height)
}
import UIKit
class ViewController: UIViewController {
var imageStrings:[String] = []
var myScrollView:UIScrollView!
#IBOutlet weak var previewView: UIImageView!
var scrollWidth : CGFloat = 320
let scrollHeight : CGFloat = 100
let thumbNailWidth : CGFloat = 80
let thumbNailHeight : CGFloat = 80
let padding: CGFloat = 10
override func viewDidLoad() {
super.viewDidLoad()
imageStrings = ["image01","image02","image03","image04","image05","image06","image07","image08"]
scrollWidth = self.view.frame.width
//setup scrollView
myScrollView = UIScrollView(frame: CGRectMake(0, self.view.frame.height - scrollHeight, scrollWidth, scrollHeight))
//setup content size for scroll view
let contentSizeWidth:CGFloat = (thumbNailWidth + padding) * (CGFloat(imageStrings.count))
let contentSize = CGSize(width: contentSizeWidth ,height: thumbNailHeight)
myScrollView.contentSize = contentSize
myScrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
for(index,value) in enumerate(imageStrings) {
var button:UIButton = UIButton.buttonWithType(.Custom) as! UIButton
//calculate x for uibutton
var xButton = CGFloat(padding * (CGFloat(index) + 1) + (CGFloat(index) * thumbNailWidth))
button.frame = CGRectMake(xButton,padding, thumbNailWidth, thumbNailHeight)
button.tag = index
let image = UIImage(named:value)
button.setBackgroundImage(image, forState: .Normal)
button.addTarget(self, action: Selector("changeImage:"), forControlEvents: .TouchUpInside)
myScrollView.addSubview(button)
}
previewView.image = UIImage(named: imageStrings[0])
self.view.addSubview(myScrollView)
}
// Do any additional setup after loading the view, typically from a nib.
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func changeImage(sender:UIButton){
let name = imageStrings[sender.tag]
previewView.image = UIImage(named: name)
}
}
Its easy with minimal use of storyboard. You can avoid that rather easily. All you need are:
Scroll view
Horizontal stack view
Set the constraints of the above as shown in the project
A number of buttons - as many view controllers that need to be displayed.
A container view - this will be the view that will hold the active view controller.
Please refer to this project for some sample code:
https://github.com/equitronix/horizontalScrollMenu
//make that variable gloabl
let button = UIButton.init(type: .custom)
var arrMmenu : NSMutableArray = []
var selectedIndex : Int = 0
#IBOutlet weak var btnScrollView: UIScrollView!
var lineArray : NSMutableArray = []
var buttonArray : NSMutableArray = []
//Call buttonCreated()
//MARK:- Create an Horizontral LayOut
func buttonCreated()
{
btnScrollView.contentSize.width = 0
namesOfMenu = ["GMC","GPA","GTL"]
var scrollwidth: CGFloat = 10.0
for j in 0..<namesOfMenu.count
{
let name = namesOfMenu[j] as! String
let size : CGSize? = name.size(withAttributes : [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 10.0)])
let textsize = CGSize(width : CGFloat(ceilf(Float(size!.width))), height : CGFloat(ceilf(Float(size!.height))))
var strikwidth : CGFloat = textsize.width
strikwidth = textsize.width + 30
let frame = CGRect(x: scrollwidth , y : CGFloat(7),width :CGFloat(strikwidth + 20) , height :CGFloat(20))
let frameLine = CGRect(x: scrollwidth , y : CGFloat(30),width :CGFloat(strikwidth + 20) , height :CGFloat(2))
let button = UIButton(type: .custom)
let line = UIView()
line.frame = frameLine
button.tag = j
view.tag = j
button.frame = frame
line .backgroundColor = UIColor.red
button.backgroundColor = UIColor.red
button.setTitleColor(UIColor.white, for: UIControlState.normal)
button.layer.borderColor = UIColor.white.cgColor
button.titleLabel?.textAlignment = .center
button.addTarget(self, action: #selector(self.buttonEvent(_:)), for: .touchUpInside)
button.setTitle(name, for : .normal)
scrollwidth = scrollwidth + strikwidth + 30
let strofMenu = namesOfMenu[selectedIndex] as! String
if (j == selectedIndex)
{
if(strofMenu == "GMC")
{
// apicall()
}
line.backgroundColor = hexStringToUIColor(hex: "#3174C7")
button.backgroundColor = UIColor.clear
button.setTitleColor(hexStringToUIColor(hex: "#3174C7"), for: UIControlState.normal)
}else
{
line.backgroundColor = UIColor.clear
button.backgroundColor = UIColor.clear
button.setTitleColor(MyConstant.Color.dark_gray_shade, for: UIControlState.normal)
}
button.titleLabel?.font = MyConstant.fontApp.Regular
buttonArray.add(button)
lineArray.add(line)
btnScrollView.addSubview(button)
btnScrollView.addSubview(line)
}
btnScrollView.contentSize = CGSize(width : CGFloat(scrollwidth), height : CGFloat(40.0))
btnScrollView.isPagingEnabled = false
btnScrollView.showsHorizontalScrollIndicator = false
btnScrollView.showsVerticalScrollIndicator = false
}
//MARK:- Button Event
#objc func buttonEvent(_ sender : UIButton)
{
let index = sender.tag
selectedIndex = index
let getRepoName = namesOfMenu[index] as! String
print(getRepoName)
for i in 0..<buttonArray.count
{
let buttonone : UIButton = (buttonArray[i] as! UIButton)
let line : UIView = (lineArray[i]) as! UIView
if i == selectedIndex
{
buttonone.backgroundColor = UIColor.clear
line.backgroundColor = hexStringToUIColor(hex: "#3174C7")
buttonone.setTitleColor(hexStringToUIColor(hex: "#3174C7"), for: .normal)
//
// if(getRepoName == "GMC")
// {
// clickedCellIndexes.add(0)
//
// arrmutablefordata.removeAllObjects()
// tblhome.reloadData()
// apicall()
// }
//buttonone.titleLabel
}else
{
buttonone.backgroundColor = UIColor.clear
line.backgroundColor = UIColor.clear
buttonone.setTitleColor(MyConstant.Color.dark_gray_shade, for: .normal)
}
}
}
Doing it from the storyboard using scroll view and stack views makes this a very simple solution. Along with a bunch of sub view controllers and transitions. I have posted sample code on GitHub. Please take a look here:
https://github.com/equitronix/horizontalScrollMenu
Let me know if this works.

Resources