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

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
}

Related

Swift. Error updating UITextView in UITableViewCell

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

Messagekit Navigation bar is not showing up

How can i show the default or custom navigation bar ? tried everything but nothing works , It seems like nothing is on the top , its a messageViewcontroller of messagekit and couldn't find any delegate method for navigation bar , it would be nice if someone educate me about this ..
My Code
override func viewDidLoad() {
messagesCollectionView = MessagesCollectionView(frame: .zero, collectionViewLayout: CustomMessagesFlowLayout())
messagesCollectionView.register(CustomCell.self)
super.viewDidLoad()
messagesCollectionView.messagesDataSource = self
messagesCollectionView.messagesLayoutDelegate = self
messagesCollectionView.messagesDisplayDelegate = self
messagesCollectionView.messageCellDelegate = self
messageInputBar.delegate = self
configureMessageInputBar()
configureInputBarItems()
updateTitleView(title: "Hanzala", subtitle: "Online")
}
import UIKit
extension UIViewController {
func updateTitleView(title: String, subtitle: String?, baseColor: UIColor = .white) {
let titleLabel = UILabel(frame: CGRect(x: 0, y: -2, width: 0, height: 0))
titleLabel.backgroundColor = UIColor.clear
titleLabel.textColor = baseColor
titleLabel.font = UIFont.systemFont(ofSize: 15)
titleLabel.text = title
titleLabel.textAlignment = .center
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.sizeToFit()
let subtitleLabel = UILabel(frame: CGRect(x: 0, y: 18, width: 0, height: 0))
subtitleLabel.textColor = baseColor.withAlphaComponent(0.95)
subtitleLabel.font = UIFont.systemFont(ofSize: 12)
subtitleLabel.text = subtitle
subtitleLabel.textAlignment = .center
subtitleLabel.adjustsFontSizeToFitWidth = true
subtitleLabel.sizeToFit()
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: max(titleLabel.frame.size.width, subtitleLabel.frame.size.width), height: 30))
titleView.addSubview(titleLabel)
if subtitle != nil {
titleView.addSubview(subtitleLabel)
} else {
titleLabel.frame = titleView.frame
}
let widthDiff = subtitleLabel.frame.size.width - titleLabel.frame.size.width
if widthDiff < 0 {
let newX = widthDiff / 2
subtitleLabel.frame.origin.x = abs(newX)
} else {
let newX = widthDiff / 2
titleLabel.frame.origin.x = newX
}
navigationItem.titleView = titleView
}
}
I want the navigation bar like this
Pushing ChatViewController in NavigationController
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let model = Api.Params.chatUser[indexPath.row]
openConversation(model)
}
func openConversation(_ model: ChatUser) {
Api.Params.inputRecieverId = model.userId
let id = String(requestManager.instance.userID)
let vc = ChatViewController(recieverId: model.userId, senderId: id, conversationId: "Eman-Conversation-\(id)-\(model.userId)")
vc.title = model.username
vc.navigationItem.largeTitleDisplayMode = .never
navigationController?.pushViewController(vc, animated: true)
}
You've to embed the MessageViewcontroller inside a UINavigationController and use it.
let navigationController = UINavigationController(rootViewController: MessageViewcontroller())
If the controller that you're pushing MessageViewcontroller onto already has a navigationController then push the MessageViewcontroller into the navigational stack instead of presenting.
let messageViewcontroller = MessageViewcontroller()
navigationController?.pushViewController(messageViewcontroller, animated: true)

How to increase the width of custom cells in UITableView

I have created the UITableView with the custom UITableViewCell. But the problem which I am getting is the width of the cells is not the frame width though I have assigned in the CGReact. Please have a look over my code :
CustomTableViewCell Class:
import UIKit
class CustomTableViewCell: UITableViewCell {
lazy var backView : UIView = {
let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width, height: 76))
view.backgroundColor = .red
view.layer.applySketchShadow()
return view
}()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
lazy var iconTime : UIImageView = {
var object = UIImageView(frame: CGRect(x: 10, y: 54, width: 12, height: 12))
object.image = #imageLiteral(resourceName: "clock")
return object
}()
lazy var notification : UILabel = {
var object = UILabel(frame: CGRect(x: 10, y: 7, width: backView.frame.width, height: 40))
object.adjustsFontSizeToFitWidth = true
object.minimumScaleFactor = 0.5
object.font = object.font.withSize(28.0)
object.numberOfLines = 3
return object
}()
lazy var notificationTime : UILabel = {
var object = UILabel(frame: CGRect(x: 30, y: 40, width: backView.frame.width, height: 40))
object.adjustsFontSizeToFitWidth = true
object.minimumScaleFactor = 0.5
object.font = object.font.withSize(12.0)
return object
}()
override func layoutSubviews() {
contentView.backgroundColor = UIColor.clear
backgroundColor = UIColor.clear
backView.layer.cornerRadius = 5
backView.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
addSubview(backView)
[notification, notificationTime, iconTime].forEach(backView.addSubview(_:))
}
}
And my view controller as follows :
import UIKit
class UserModal {
var tableView = UITableView()
var notification: String?
var notificationTime : String?
init(notification: String, notificationTime: String) {
self.notification = notification
self.notificationTime = notificationTime
}
}
class newNotificationController : UIViewController {
var tableView = UITableView()
var userMod = [UserModal]()
override func viewDidLoad() {
super.viewDidLoad()
setTableView()
userMod.append(UserModal(notification: "Data ", notificationTime: "Time"))
userMod.append(UserModal(notification: "This is some Notification which needs to be populated in the Grid view for testing but lets see what is happening here!! ", notificationTime: "12-12-1212 12:12:12"))
userMod.append(UserModal(notification: "Data ", notificationTime: "Time"))
}
func setTableView() {
tableView.frame = self.view.frame
tableView.backgroundColor = UIColor.clear
tableView.delegate = self
tableView.dataSource = self
tableView.separatorColor = UIColor.clear
self.view.addSubview(tableView)
tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "cell")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
}
extension newNotificationController: UITableViewDelegate , UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userMod.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? CustomTableViewCell else { fatalError("Unable to populate Notification History")}
cell.notification.text = userMod[indexPath.row].notification
cell.notificationTime.text = userMod[indexPath.row].notificationTime
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 85
}
}
Please have a look over the result:
I am not getting it why the width of my cells is the width of the frame. Any help will be highly appreciated. Thanks!!
The problem is in this code is frame width, somehow the width of the self is not the width of a device, so because of this, you are facing this issue.
lazy var backView : UIView = {
let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width, height: 76))
view.backgroundColor = .red
view.layer.applySketchShadow()
return view
}()
To resolve this issue you can set frame like this
let view = UIView(frame: CGRect(x: 10, y: 6, width: UIScreen.main.bounds.size.width - 10, height: 76))
You set the width your view
UIView(frame: CGRect(x: 5, y: 6, width: self.frame.width - 10,
height: 76))
tableView.frame = CGRect(x: 0, y: 0, width:
self.view.frame.size.width, height: self.view.frame.size.height)
you need to give constraint to the tableview. Top, Leading, Trailing, Bottom.
put this tableView.translatesAutoresizingMaskIntoConstraints = false line in your function
func setTableView() {
tableView.frame = self.view.frame
tableView.backgroundColor = UIColor.clear
tableView.delegate = self
tableView.dataSource = self
tableView.separatorColor = UIColor.clear
self.view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false //add this line
tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "cell")
}
and change width: UIScreen.main.bounds.size.width - 10 it.
thanks..

How to fix wrong indexPath returned by didSelectRowAt?

I have a UITableView; without a tableHeaderView tapping a row and triggering didSelectRowAt returns the correct index path.
When I set the tableHeaderView property, didSelectRowAt either does not fire or returns the tappedRow + 2. Where am I going wrong?
Here is my code
class MenuController: UIViewController {
// Mark -- Properties
var tableView: UITableView!
var delegate: HomeControllerDelegate?
var headerView: HeaderView? = nil
var user: User? = nil
// Mark -- Init
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
if let user = self.user {
populateMenuHeader(email: user.email, firstName: user.firstName, lastName: user.lastName, imageUrl: user.imageUrl)
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
//updateHeaderViewHeight(for: tableView.tableHeaderView)
}
func updateHeaderViewHeight(for header: UIView?) {
guard let headerView = headerView else { return }
headerView.frame.size.height = 170
}
func populateMenuHeader(email: String, firstName: String, lastName: String, imageUrl: String) {
headerView?.emailLabel?.text = email
headerView?.nameLabel?.text = "\(firstName) \(lastName)"
let request = ImageRequest(
url: URL(string: imageUrl)!,
processors: [
ImageProcessor.Resize(size: CGSize(width: 70, height: 70)),
ImageProcessor.Circle()
]
)
Nuke.loadImage(with: request, into: headerView!.imageView!)
}
// Mark -- Handlers
func configureTableView() {
// Create Material Header
headerView = HeaderView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 170))
//headerView?.heightAnchor.constraint(equalToConstant: 170).isActive = true
headerView?.translatesAutoresizingMaskIntoConstraints = false
tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.tableHeaderView = headerView
tableView.sectionHeaderHeight = 170
tableView.register(MenuOptionCell.self, forCellReuseIdentifier: reuseIdentifier)
tableView.backgroundColor = .darkGray
tableView.separatorStyle = .none
tableView.rowHeight = 80
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
}
}
extension MenuController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! MenuOptionCell
let menuOption = MenuOption(rawValue: indexPath.row)
cell.descriptionLabel.text = menuOption?.description
cell.iconImageView.image = menuOption?.image
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let row = indexPath.row
print("tapped row: \(row)")
let menuOption = MenuOption(rawValue: row)
delegate?.handleMenuToggle(forMenuOption: menuOption)
}
}
class CustomView: UIView {
override func draw(_ rect: CGRect) {
super.draw(rect)
if let context = UIGraphicsGetCurrentContext() {
context.setStrokeColor(UIColor.white.cgColor)
context.setLineWidth(1)
context.move(to: CGPoint(x: 0, y: bounds.height))
context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
context.strokePath()
}
}
}
class HeaderView : UIView {
var imageView: UIImageView? = nil
var nameLabel: UILabel? = nil
var emailLabel: UILabel? = nil
override init(frame: CGRect) {
super.init(frame: frame)
imageView = UIImageView()
imageView?.translatesAutoresizingMaskIntoConstraints = false
nameLabel = UILabel()
nameLabel?.translatesAutoresizingMaskIntoConstraints = false
nameLabel?.font = UIFont(name: "Avenir-Light", size: 20)
nameLabel?.text = "Test name"
nameLabel?.textColor = .white
emailLabel = UILabel()
emailLabel?.translatesAutoresizingMaskIntoConstraints = false
emailLabel?.textColor = .white
emailLabel?.font = UIFont(name: "Avenir-Light", size: 15)
emailLabel?.text = "testemail#gmail.com"
self.addSubview(imageView!)
self.addSubview(nameLabel!)
self.addSubview(emailLabel!)
let lineView = CustomView(frame: CGRect(x: 0, y: frame.height - 1, width: frame.width, height: 1))
self.addSubview(lineView)
imageView?.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
imageView?.topAnchor.constraint(equalTo: topAnchor, constant: 20).isActive = true
imageView?.widthAnchor.constraint(equalTo: widthAnchor, constant: 70).isActive = true
imageView?.heightAnchor.constraint(equalTo: heightAnchor, constant: 70).isActive = true
nameLabel?.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
nameLabel?.topAnchor.constraint(equalTo: imageView!.bottomAnchor, constant: 10).isActive = true
emailLabel?.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
emailLabel?.topAnchor.constraint(equalTo: nameLabel!.bottomAnchor, constant: 5).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
The problem appears to be due to the fact that you are not properly setting the height of the header view. The documentation for tableHeaderView states:
When assigning a view to this property, set the height of that view to a nonzero value. The table view respects only the height of your view's frame rectangle; it adjusts the width of your header view automatically to match the table view's width.
Update your header view code:
Change:
headerView = HeaderView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 170))
//headerView?.heightAnchor.constraint(equalToConstant: 170).isActive = true
headerView?.translatesAutoresizingMaskIntoConstraints = false
...
tableView.sectionHeaderHeight = 170
to just:
headerView = HeaderView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 170))
That's it. No need to mess with constraints. No need to set the unrelated section height. Just give the header view's frame the desired height.

Adding tableview to scrollview with paging enabled.

I am creating an app and one of its screen needs to have a UIScrollView with paging. In each page of the scrollview it needs to have a UITableView as shown:
I have accomplished to create a scrollview with paging enabled (programatically) but the problem I am facing is:
If I create a simple UILabel and add it to the pages, it works fine. But if I create a tableview and add it to the pages (if this term makes sense) nothing gets displayed on the screen. Here is my code with comments on related places for better understanding:
class SampleViewController: UIViewController, UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource {
let screenHeight = UIScreen.main.bounds.height
let screenWidth = UIScreen.main.bounds.width
let scrollView = UIScrollView()
let tableView = UITableView()
var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat", "Dog", "Cat", "Kitten", "Lion", "Tiger", "Owl", "Skylark", "Snail", "Cub", "Zebra"]
var frame: CGRect = CGRect(x:0, y:0, width:0, height:0)
var pageControl : UIPageControl = UIPageControl(frame: CGRect(x:50,y: 300, width:200, height:50))
let cellReuseIdentifier = "cell"
override func viewDidLoad() {
super.viewDidLoad()
let frameOfScrollView : CGRect = CGRect(x:0, y:0, width:screenWidth, height:screenHeight)
scrollView.frame = frameOfScrollView
scrollView.delegate = self
scrollView.isPagingEnabled = true
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(scrollView)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
self.scrollView.contentSize = CGSize(width:self.scrollView.frame.size.width * 4,height: self.scrollView.frame.size.height)
for index in 0..<4 {
frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
frame.size = self.scrollView.frame.size
// THIS THING DOESN'T WORK
tableView.frame = frame
self.scrollView .addSubview(tableView)
// THIS THING WORKS
let subView = UILabel(frame: frame)
subView.backgroundColor = colors[index]
subView.text = "how are you?"
self.scrollView .addSubview(subview)
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = self.animals[indexPath.row]
return cell
}
}
What am I doing wrong? Did I miss anything regrading tableview?
Note: I have created views programmatically because I didn't have much understanding regarding which constraints shall I use in order to add paging to scrollview because I am a newbie to iOS. If anyone can provide some solution to my problem in terms of auto layouts, it would be welcomed.
Basically the purpose is just to achieve what is shown in the screenshot attached above. Any alternate approach if applicable, would also be appreciated.
No need to declare global variable for UITableview.
Replace viewDidLoad() to achieve your requirement.
override func viewDidLoad() {
super.viewDidLoad()
let frameOfScrollView : CGRect = CGRect(x:0, y:0, width:screenWidth, height:screenHeight)
scrollView.frame = frameOfScrollView
scrollView.delegate = self
scrollView.isPagingEnabled = true
// tableView.delegate = self
// tableView.dataSource = self
self.view.addSubview(scrollView)
// self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
self.scrollView.contentSize = CGSize(width:self.scrollView.frame.size.width * 4,height: self.scrollView.frame.size.height)
for index in 0..<4 {
frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
frame.size = self.scrollView.frame.size
let tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
tableView.frame = frame
self.scrollView .addSubview(tableView)
//// // THIS THING DOESN'T WORK
// tableView.frame = frame
// self.scrollView .addSubview(tableView)
// THIS THING WORKS
// let subView = UILabel(frame: frame)
// subView.backgroundColor = colors[index]
// subView.text = "how are you?"
// self.scrollView.addSubview(subView)
}
}
Replace
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
with
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
Remove
let tableView = UITableView()

Resources