Recently I want to implement the UI of Image and text slide show, because of my personal reasons: App pages are implemented by program code. I spent some time researching the usage of UIScrollView and UIPageControl, and found this link(How to create a Scroll View with a page control using swift?) is very informative, but the code is in My environment is not working, the SubView of UIScrollView has not been displayed correctly, and there is a problem with sliding to switch pages. I spent a lot of time searching for the answers to the questions, and I didn't find any valid information.
update my solution:
After some practice, the problem is solved, I will post the notes and solutions.
Just remember:
1、Your UIScrollView must have left (or leading) / top / width / height values.
2、The content elements of your UIScrollView need define the bounds of the contentSize-but they do so with the bottom & right (trailing) constraints.
3、The middle SubView of each UIScrollView requires some left (or leading) and right (trailing) constraints. See the code example for details.
class NTDummyVC: UIViewController, UIScrollViewDelegate {
let SCROLLVIEW_HIGHT:CGFloat = 500
let PAGECONTROL_WIDTH:CGFloat = 200
let PAGECONTROL_HIGHT:CGFloat = 50
var scrollView = UIScrollView()
var pageControl = UIPageControl()
var contentViewArray: NSMutableArray = NSMutableArray()
var imageArray: NSArray = ["ImageName one",
"ImageName two",
"ImageName three"]
var titleArray: NSArray = [NSLocalizedString("Title one", comment: ""),
NSLocalizedString("Title two", comment: ""),
NSLocalizedString("Title three", comment: "")]
var subTitleArray: NSArray = [NSLocalizedString("SubTitle one", comment: ""),
NSLocalizedString("SubTitle two", comment: ""),
NSLocalizedString("SubTitle three", comment: "")]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
initScrollView()
initPageControl()
loadScrollView()
//After loading all SubViews, update the contentSize of UIScrollView according to the number of Subviews.
let scrollViewWidth = scrollView.frame.size.width * CGFloat(getPageCount())
self.scrollView.contentSize = CGSize(width: scrollViewWidth, height: scrollView.frame.size.height)
}
func getTopbarHeight() -> CGFloat {
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let navigationBarHeight = navigationController?.navigationBar.frame.height ?? 0.0
return statusBarHeight + navigationBarHeight
}
func getPageCount() -> Int {
var pageCount = 0
pageCount = imageArray.count
if titleArray.count < pageCount {
pageCount = titleArray.count
}
if subTitleArray.count < pageCount {
pageCount = subTitleArray.count
}
return pageCount
}
func initScrollView() {
self.scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: SCROLLVIEW_HIGHT))
self.scrollView.delegate = self
self.scrollView.bounces = false
self.scrollView.isPagingEnabled = true
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.showsHorizontalScrollIndicator = false
self.view.addSubview(self.scrollView)
//Constraints for ScrollView, by snapkit tool.
self.scrollView.snp.makeConstraints { (make) in
make.width.equalToSuperview()
make.height.equalTo(SCROLLVIEW_HIGHT)
make.top.equalToSuperview().offset(getTopbarHeight())
make.leading.equalToSuperview()
}
}
func initPageControl() {
self.pageControl.numberOfPages = getPageCount()
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.gray
self.pageControl.pageIndicatorTintColor = UIColor.gray
self.pageControl.currentPageIndicatorTintColor = UIColor.green
self.view.addSubview(pageControl)
//Constraint displayed in the center, by snapkit tool.
self.pageControl.snp.makeConstraints { (make) in
make.width.equalTo(PAGECONTROL_WIDTH)
make.height.equalTo(PAGECONTROL_HIGHT)
make.top.equalTo(self.scrollView.snp.bottom).offset(10)
make.leading.equalToSuperview()
make.trailing.equalToSuperview()
make.centerX.equalToSuperview()
}
pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)
}
func loadScrollView() {
let pageCount = getPageCount()
for index in 0...(pageCount - 1) {
var frame = CGRect.zero
frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
frame.origin.y = 0
frame.size = self.scrollView.frame.size
let contentView = UIView(frame: frame)
contentView.backgroundColor = .white
self.scrollView.addSubview(contentView)
//Constraints for SubView, by snapkit tool.
//Do’t add extra constraints such as top, bottom, width, height, etc., which will cause abnormal display.
contentView.snp.makeConstraints { (make) in
make.width.equalTo(UIUtils.screenWidth())
make.height.equalTo(self.scrollView.snp.height)
if index >= 1 {
let view:UIView = contentViewArray.object(at: index - 1) as! UIView
make.leading.equalTo(view.snp.trailing)
} else {
make.leading.equalTo(0)
}
if index == (pageCount - 1) {
make.trailing.equalTo(0)
}
}
let imageView = UIImageView(image: UIImage(named: imageArray[index] as! String))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = UIViewContentMode.scaleAspectFit
contentView.addSubview(imageView)
imageView.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
}
let titleLabel = UILabel()
titleLabel.font = UIFont.boldSystemFont(ofSize: 18)
titleLabel.text = titleArray[index] as? String
titleLabel.textColor = .black
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = .byWordWrapping
titleLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(imageView.snp.bottom).offset(30)
make.leading.equalToSuperview().offset(30)
make.trailing.equalToSuperview().offset(-30)
}
let subTitleLabel = UILabel()
subTitleLabel.font = UIFont.boldSystemFont(ofSize: 12)
subTitleLabel.text = subTitleArray[index] as? String
subTitleLabel.textColor = UIUtils.color(2)
subTitleLabel.numberOfLines = 0
subTitleLabel.lineBreakMode = .byWordWrapping
subTitleLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(subTitleLabel)
subTitleLabel.snp.makeConstraints { (make) in
make.top.equalTo(titleLabel.snp.bottom).offset(5)
make.leading.equalToSuperview().offset(30)
make.trailing.equalToSuperview().offset(-30)
}
if (contentViewArray.contains(contentView)) {
contentViewArray.replaceObject(at: contentViewArray.index(of: contentView), with: contentView)
} else {
contentViewArray.insert(contentView, at: index)
}
}
}
// MARK : To Change while clicking on page control
#objc func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPoint(x:x, y:0), animated: true)
}
// MARK : When UIScrollView slides over, update PageControl
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
}
Hope to help people who encounter the same problem.
Related
This is my code:
class UINavigationControllerCustom : UINavigationController {
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews();
navigationBar.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 120);
}
}
class PreferenceInput: UIViewController {
override func viewDidLoad() {
let l1 = UILabel()
l1.backgroundColor = .clear
l1.numberOfLines = 1
l1.font = UIFont.boldSystemFont(ofSize: 30.0)
l1.textAlignment = .left
l1.textColor = .black
l1.text = "Bold title"
l1.sizeToFit();
let l2 = UILabel()
l2.backgroundColor = .clear
l2.numberOfLines = 2
l2.font = UIFont.boldSystemFont(ofSize: 16.0)
l2.textAlignment = .left
l2.textColor = .darkGray;
l2.text = "This is a\nmultiline string for the navBar"
l2.sizeToFit();
let tView = UIStackView(arrangedSubviews: [l1,l2]);
tView.axis = .vertical;
let spacer = UIView()
let constraint = spacer.widthAnchor.constraint(greaterThanOrEqualToConstant: CGFloat.greatestFiniteMagnitude)
constraint.isActive = true
constraint.priority = .defaultLow
let stack = UIStackView(arrangedSubviews: [tView, spacer])
stack.axis = .horizontal
navigationItem.titleView = stack
navigationItem.titleView.sizeToFit();
}
}
And this is what I get:
I can set the height of the navigation bar but how and where should I set the constraint to stretch the height in respect of the given 120px of the custom navigation controller?
I want to provide an individual height of the navigation bar.
My code tutorial works for scrolling horizontally with ScrollView.
I would like to make it with ViewControllers (instead of views) from my Storyboard.
And I would like to add a vertical ScrollView (To move from center to right or left = ScrollView horizontal, and to move from center to top or bottom (vertically).
Is that possible? Could someone give me a hint ?
Thanks
For information, this is my code :
import UIKit
class ViewController: UIViewController {
lazy var view0: UIView = {
let view = UIView()
view.backgroundColor = .systemTeal
let label = UILabel()
label.text = "Page 0"
label.textAlignment = .center
view.addSubview(label)
label.edgeTo(view: view)
return view
}()
lazy var view1: UIView = {
let view = UIView()
view.backgroundColor = .systemPink
let label = UILabel()
label.text = "Page 1"
label.textAlignment = .center
view.addSubview(label)
label.edgeTo(view: view)
return view
}()
lazy var view2: UIView = {
let view = UIView()
view.backgroundColor = .systemYellow
let label = UILabel()
label.text = "Page 2"
label.textAlignment = .center
view.addSubview(label)
label.edgeTo(view: view)
return view
}()
lazy var views = [view0, view1, view2]
lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.isPagingEnabled = true
scrollView.contentSize = CGSize(width: view.frame.width * CGFloat(views.count), height: view.frame.height)
for i in 0..<views.count {
scrollView.addSubview(views[i])
views[i].frame = CGRect(x: view.frame.width * CGFloat(i), y: 0, width: view.frame.width, height: view.frame.height)
}
scrollView.delegate = self
return scrollView
}()
lazy var pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.numberOfPages = views.count
pageControl.currentPage = 0
pageControl.addTarget(self, action: #selector(pageControlTapHandler(sender:)), for: .touchUpInside)
return pageControl
}()
#objc
func pageControlTapHandler(sender: UIPageControl) {
scrollView.scrollTo(horizontalPage: sender.currentPage, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(scrollView)
scrollView.edgeTo(view: view)
view.addSubview(pageControl)
pageControl.pinTo(view)
}
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageIndex = round(scrollView.contentOffset.x / view.frame.width)
pageControl.currentPage = Int(pageIndex)
}
I am creating a UIView programtically that is scaled and translated to the center of my view. I am then adding subviews (UILabel's) to that view programatically and the issue I have encountered is that the text for the UILabel's is stretched and difficult to read. I have tried to set autoresizeSubviews = false however this did not have any effect. I have also tried setting the number of lines but this did not have any affect either. I wanted to know if there was a possible solution to this problem that perhaps I am overlooking. Below is my code...
Here i instantiate each UI object to be used on view including view itself
//create lazy vars for UIView that is instantiated until it is initialized
lazy var enlargedView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 12.0
view.clipsToBounds = true
return view
}()
lazy var profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.frame = CGRect(x: self.enlargedView.center.x, y: self.enlargedView.bounds.origin.y + 20.0, width: self.enlargedView.bounds.width * 0.4, height: self.enlargedView.bounds.width * 0.4)
imageView.layer.cornerRadius = imageView.frame.width / 2
imageView.clipsToBounds = true
imageView.layer.borderColor = UIColor.black.cgColor
imageView.layer.borderWidth = 1.0
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
lazy var usernameLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.textColor = UIColor.black
let font = UIFont(name: Constants.Fonts.GILL_SANS_SEMIBOLD, size: 8.0)
let fontMetrics = UIFontMetrics(forTextStyle: .body)
label.font = fontMetrics.scaledFont(for: font!)
label.textAlignment = .center
//label.sizeToFit()
label.translatesAutoresizingMaskIntoConstraints = false
return label
} ()
lazy var userDataLabel: UILabel = {
let label = UILabel()
//creates implicit height for label
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.textColor = UIColor.black
let font = UIFont(name: Constants.Fonts.GILL_SANS, size: 10.0)
let fontMetrics = UIFontMetrics(forTextStyle: .body)
label.font = fontMetrics.scaledFont(for: font!)
label.textAlignment = .center
label.sizeToFit()
label.translatesAutoresizingMaskIntoConstraints = false
return label
} ()
Next I create animation for view to scale and translate once a collectionView cell is tapped
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SearchCell", for: indexPath) as! SearchCell
let currentFrame = cell.frame
let selectedUser = userNameArr[indexPath.row]
enlargedView.frame = currentFrame
let backgroundView = UIView(frame: self.view.bounds)
backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: {
self.view.addSubview(self.enlargedView)
//translate view to center of screen
self.enlargedView.center = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
//while view is being translated background subview should be inserted
self.view.insertSubview(backgroundView, belowSubview: self.enlargedView)
self.enlargedView.transform = CGAffineTransform(scaleX: 2.5, y: 2.5)
}) { (viewWasEnlarged) in
if viewWasEnlarged {
if let profile = selectedUser.user_photo_url {
self.profileImageView.kf.setImage(with: URL(string:Constants.Server.MEDIA_URL + profile))
} else {
self.profileImageView.image = UIImage(named: "user_icon")
}
self.enlargedView.addSubview(self.profileImageView)
self.profileImageView.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalTo(self.enlargedView.snp.top).offset(20.0)
make.width.equalTo(self.enlargedView.snp.width).multipliedBy(0.4)
make.height.equalTo(self.enlargedView.snp.width).multipliedBy(0.4)
}
//USERNAME label
self.usernameLabel.text = selectedUser.user_name!
self.enlargedView.addSubview(self.usernameLabel)
self.usernameLabel.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.width.equalTo(self.enlargedView.snp.width).multipliedBy(0.9)
make.top.equalTo(self.profileImageView.snp.bottom).offset(5.0)
}
//reset enlarged view back to original value
self.usernameLabel.transform = CGAffineTransform.identity
//USER DATA label
var userAge = ""
var userRelationshipStatus = ""
if let userYear = selectedUser.user_birthday {
let yr = self.calendar.dateComponents([.year], from: userYear).year
userAge = "\(yr!)"
}
if let status = selectedUser.user_stats {
userRelationshipStatus = status
}
self.userDataLabel.text = userAge + " | " + userRelationshipStatus
self.enlargedView.addSubview(self.userDataLabel)
self.userDataLabel.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.width.equalTo(self.enlargedView.snp.width).multipliedBy(0.2)
make.top.equalTo(self.usernameLabel.snp.bottom).offset(3.0)
}
//create label to show HUB as well
//create bio
//show Path??
}
}
The imageView is unaffected however the text itself is not reflected correctly
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.
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.