Add UIView and UITableView programmatically - ios

I am trying to make this, as in the first picture:
Image 1
Image 2
But the view somehow does not show up like I want it to. Here you can see my full project code:
import UIKit
import RealmSwift
import CVCalendar
class Test: UIViewController, UITableViewDelegate, UITableViewDataSource {
var myTableView: UITableView = UITableView()
var itemsToLoad: [String] = ["One", "Two", "Three"]
var myView = UIView()
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red: 4/255, green: 4/255, blue: 4/255, alpha: 1.0)
self.navigationController?.navigationBar.barStyle = .black
self.navigationController?.navigationBar.tintColor = UIColor.white
self.navigationItem.title = "Test"
self.navigationController?.navigationBar.prefersLargeTitles = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Get main screen bounds
let screenSize: CGRect = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
myView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 150)
myView.backgroundColor = .black
self.view.addSubview(myView)
myTableView.frame = CGRect(x: 0, y: 50, width: screenWidth, height: screenHeight-50);
myTableView.dataSource = self
myTableView.delegate = self
myTableView.backgroundColor = .blue
myTableView.layer.borderWidth = 3
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(myTableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return itemsToLoad.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = self.itemsToLoad[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("User selected table row \(indexPath.row) and item \(itemsToLoad[indexPath.row])")
}
}
Why won't it show up? The first picture is how I want it, then second picture is how it looks now.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if self.itemsToLoad[indexPath.row] != nil {
cell.textLabel?.text = self.itemsToLoad[indexPath.row]
cell.backgroundColor = .white
}else {
cell.backgroundColor = .blue
}
return cell
}

Related

Why isn’t my custom UITableView cell showing?

I’ve implemented a custom cell for a UITableView, but when I run the Playground it’s just a standard table. It’s probably something stupid simple, but I’m very new to UIKit and somewhat new to Swift.
Also, I’ve tried to implement a “sticky header”, but no matter what I try the header scrolls with the rest of the table.
import UIKit
import PlaygroundSupport
class ViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 19
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CardCell = tableView.dequeueReusableCell(withIdentifier: "CardCell", for: indexPath) as! CardCell
cell.messageLabel.text = "yo"
return cell
}
var convoTableView = UITableView()
override func viewDidLoad(){
super.viewDidLoad()
convoTableView = UITableView(frame: self.view.bounds, style:
UITableView.Style.plain)
convoTableView.backgroundColor = UIColor.white
convoTableView.register(CardCell.self, forCellReuseIdentifier: "CardCell")
let header = UIView(frame: CGRect(x: 0, y: 0, width: convoTableView.frame.width, height: 100))
header.backgroundColor = .red
self.convoTableView.delegate = self
self.convoTableView.dataSource = self
let yourLabel = UILabel(frame: CGRect(x: 10, y: 0, width: 100, height: 100))
yourLabel.textColor = UIColor.black
yourLabel.backgroundColor = UIColor.white
yourLabel.text = "mylabel text"
header.addSubview(yourLabel)
convoTableView.tableHeaderView = header
convoTableView.estimatedSectionHeaderHeight = 40.0
self.view.addSubview(convoTableView)
}
}
class CardCell: UITableViewCell {
let messageLabel:UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 14)
label.clipsToBounds = true
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let dateLabel:UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 8)
label.clipsToBounds = true
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let containerView:UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.clipsToBounds = true
return view
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
containerView.addSubview(messageLabel)
containerView.addSubview(dateLabel)
self.contentView.addSubview(containerView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
PlaygroundPage.current.liveView = ViewController()
Here's all the code you need here to make a custom cell and sticky header:
import UIKit
import PlaygroundSupport
class ViewController: UITableViewController {
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
view.backgroundColor = .purple
return view
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
50
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
19
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CardCell", for: indexPath) as! CardCell
cell.textLabel?.text = "\(indexPath.row)"
return cell
}
override func viewDidLoad(){
super.viewDidLoad()
tableView.register(CardCell.self, forCellReuseIdentifier: "CardCell")
}
}
class CardCell: UITableViewCell { }
PlaygroundPage.current.liveView = ViewController()
To make the header sticky and non-scrollable with the table view you need to take a different UIView above the table view and give the frames of the table just below the UiView.
customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView

Setup default row in tableView

I have a problem with setup default row in TableView. I just wanna always pick first element from dataSource. I tried a few solutions with "selectRow" and other but no one of them work.
Here's my code below:
class HomeVC: UIViewController{
#IBOutlet weak var btnSelectCountry: UIButton!
let transparentView = UIView()
let tableView = UITableView()
var selectedButton = UIButton()
var dataSource = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(CellClass.self, forCellReuseIdentifier: "Cell")
let index = NSIndexPath(row: 0, section: 0)
tableView.selectRow(at: index as IndexPath, animated: true, scrollPosition: .bottom)
}
func addTransparentView(frames: CGRect){
let window = UIApplication.shared.keyWindow
transparentView.frame = window?.frame ?? self.view.frame
self.view.addSubview(transparentView)
tableView.frame = CGRect(x: frames.origin.x, y: frames.origin.y + frames.height, width: frames.width, height: 0 )
self.view.addSubview(tableView)
tableView.layer.cornerRadius = 5
transparentView.backgroundColor = UIColor.black.withAlphaComponent(0.9)
tableView.reloadData()
let tapgesture = UITapGestureRecognizer(target: self, action: #selector(removeTransparentView))
transparentView.addGestureRecognizer(tapgesture)
transparentView.alpha = 0
UIView.animate(withDuration: 0.4, delay: 0.0, options: .curveEaseInOut, animations: {
self.transparentView.alpha = 0.5
self.tableView.frame = CGRect(x: frames.origin.x, y: frames.origin.y + frames.height + 5, width: frames.width, height: CGFloat(self.dataSource.count * 50))
}, completion: nil)
}
}
extension HomeVC: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = dataSource[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedButton.setTitle(dataSource[indexPath.row], for: .normal)
removeTransparentView()
}
Try replacing viewDidLoad() with this
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(CellClass.self, forCellReuseIdentifier: "Cell")
let index = IndexPath(row: 0, section: 0)
tableView(tableView, didSelectRowAt: index)
}
This will automatically trigger the didSelectRow method but you need to populate your dataSource before this or the application will crash.
You can try adding this for example in viewWillAppear()
override func viewWillAppear(_ animated: Bool) {
dataSource = ["Your", "Data"]
}

How to acces a view from tableViewCell to TableViewController

I have a UITableViewController and UITableViewCell. Now I am try to access a view from a UITableViewCell to UITableViewController by didSelectRowAt function. But I could not do it.
TableViewController
import Foundation
import UIKit
class FlipViewCon: UIViewController, UITableViewDelegate, UITableViewDataSource{
let flipCellId = "flipCellid"
let flipTableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = .green
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .gray
flipTableView.delegate = self
flipTableView.dataSource = self
flipTableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
self.view.addSubview(flipTableView)
flipTableView.register(FlipTableViewCell.self, forCellReuseIdentifier: flipCellId)
}
let countryArray = ["bangladesh", "nepal", "china", "malaysia", "thai land", "japan", "England", "canada"]
let cityArray = ["Dhake","Kathmandu", "Beijing", "Kuala Lumpur", "Bangkok", "tokeyo", "London", "Torento"]
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countryArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: flipCellId, for: indexPath) as! FlipTableViewCell
//cell.textLabel?.text = countryArray[indexPath.row]
cell.zeroLabel.text = countryArray[indexPath.row]
cell.oneLabel.text = cityArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UIView.transition(with: FlipTableViewCell.zeroView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: nil)
FlipTableViewCell.zeroView.isHidden = true
FlipTableViewCell.oneView.isHidden = false
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
UIView.transition(with: FlipTableViewCell.oneView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: nil)
FlipTableViewCell.zeroView.isHidden = false
FlipTableViewCell.oneView.isHidden = true
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.flipTableView.frame.width / 4
}
}
TableViewCell
import UIKit
class FlipTableViewCell: UITableViewCell{
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
static let zeroView = flipView(myColor: .yellow)
static let oneView = flipView(myColor: .green)
static func flipView(myColor: UIColor) -> UIView {
let view = UIView()
view.backgroundColor = myColor
return view
}
let zeroLabel: UILabel = {
let lb = UILabel()
lb.text = "Zero 0"
return lb
}()
let oneLabel: UILabel = {
let lb = UILabel()
lb.text = "one 1"
return lb
}()
func setupView(){
FlipTableViewCell.zeroView.frame = CGRect(x: 0, y: 0, width: frame.width, height:frame.height)
FlipTableViewCell.oneView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
self.addSubview(FlipTableViewCell.zeroView)
self.addSubview(FlipTableViewCell.oneView)
zeroLabel.frame = CGRect(x: 20, y: 0, width: self.frame.width - 40, height: 50)
oneLabel.frame = CGRect(x: 20, y:0, width: self.frame.width - 40, height: 50)
addSubview(zeroLabel)
addSubview(oneLabel)
}
}
Try this:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? FlipTableViewCell {
UIView.transition(with: cell.zeroView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: nil)
cell.zeroView.isHidden = true
cell.oneView.isHidden = false
}
}
Edit
I have update your FlipTableViewCell
it looks like this
class FlipTableViewCell: UITableViewCell{
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var zeroView : UIView!
var oneView : UIView!
func flipView(myColor: UIColor) -> UIView {
let view = UIView()
view.backgroundColor = myColor
return view
}
let zeroLabel: UILabel = {
let lb = UILabel()
lb.text = "Zero 0"
return lb
}()
let oneLabel: UILabel = {
let lb = UILabel()
lb.text = "one 1"
return lb
}()
func setupView(){
zeroView = flipView(myColor: .yellow)
oneView = flipView(myColor: .green)
zeroView.frame = CGRect(x: 0, y: 0, width: frame.width, height:frame.height)
oneView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
self.addSubview(zeroView)
self.addSubview(oneView)
zeroLabel.frame = CGRect(x: 20, y: 0, width: self.frame.width - 40, height: 50)
oneLabel.frame = CGRect(x: 20, y:0, width: self.frame.width - 40, height: 50)
addSubview(zeroLabel)
addSubview(oneLabel)
}
}
And Change some code in FlipViewCon
class FlipViewCon: UIViewController, UITableViewDelegate, UITableViewDataSource{
let flipCellId = "flipCellid"
let flipTableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = .green
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .gray
flipTableView.delegate = self
flipTableView.dataSource = self
flipTableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
self.view.addSubview(flipTableView)
flipTableView.register(FlipTableViewCell.self, forCellReuseIdentifier: flipCellId)
}
let countryArray = ["bangladesh", "nepal", "china", "malaysia", "thai land", "japan", "England", "canada"]
let cityArray = ["Dhake","Kathmandu", "Beijing", "Kuala Lumpur", "Bangkok", "tokeyo", "London", "Torento"]
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countryArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: flipCellId, for: indexPath) as! FlipTableViewCell
//cell.textLabel?.text = countryArray[indexPath.row]
cell.zeroLabel.text = countryArray[indexPath.row]
cell.oneLabel.text = cityArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? FlipTableViewCell {
UIView.transition(with: cell.zeroView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: nil)
cell.zeroView.isHidden = true
cell.oneView.isHidden = false
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? FlipTableViewCell {
UIView.transition(with: cell.zeroView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: nil)
cell.zeroView.isHidden = false
cell.oneView.isHidden = true
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.flipTableView.frame.width / 4
}
}
Edit2
Replace this method in above solution
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? FlipTableViewCell {
UIView.transition(with: cell.oneView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: nil)
cell.zeroView.isHidden = false
cell.oneView.isHidden = true
}
}
Hope it will work for you
Do like this
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! FlipTableViewCell
// TODO:
}
Just like all the other answers on this post, use the cellForRow(at: IndexPath) method on UITableView, to get a reference to the cells in the table view.
This method returns a UITableViewCell, if the cell is loaded (visible) and nil if the indexPath is not correct or the cell is not loaded.
The code should look like:
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
// Do something with cell.
}
TableViewController
import Foundation
import UIKit
class FlipViewCon: UIViewController, UITableViewDelegate, UITableViewDataSource{
let flipCellId = "flipCellid"
let flipTableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = .green
tableView.allowsMultipleSelection = true
return tableView
}()
let countryArray = ["India","bangladesh", "nepal", "china", "malaysia", "thai land", "japan", "England", "canada"]
let cityArray = ["Delhi","Dhake","Kathmandu", "Beijing", "Kuala Lumpur", "Bangkok", "tokeyo", "London", "Torento"]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .gray
flipTableView.delegate = self
flipTableView.dataSource = self
flipTableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
self.view.addSubview(flipTableView)
self.resetFlag()
flipTableView.register(FlipTableViewCell.self, forCellReuseIdentifier: flipCellId)
}
var flagArray : [String] = []
func resetFlag() {
flagArray.removeAll(keepingCapacity: true)
for _ in 0 ..< self.countryArray.count {
self.flagArray.append("0")
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countryArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: flipCellId, for: indexPath) as! FlipTableViewCell
cell.selectionStyle = .none
if flagArray[indexPath.row] == "0" {
cell.zeroView.isHidden = false
cell.oneView.isHidden = true
}else{
cell.zeroView.isHidden = true
cell.oneView.isHidden = false
}
cell.zeroLabel.text = countryArray[indexPath.row]
cell.oneLabel.text = cityArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? FlipTableViewCell {
self.flagArray.remove(at: indexPath.row)
self.flagArray.insert("1", at: indexPath.row)
UIView.transition(with: cell.zeroView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: { (complete) in
cell.zeroView.isHidden = true
cell.oneView.isHidden = false
})
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? FlipTableViewCell {
self.flagArray.remove(at: indexPath.row)
self.flagArray.insert("0", at: indexPath.row)
UIView.transition(with: cell.oneView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: { (complete) in
cell.zeroView.isHidden = false
cell.oneView.isHidden = true
})
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.flipTableView.frame.width / 4
}
}
TableViewCell
import UIKit
class FlipTableViewCell: UITableViewCell{
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let zeroView = flipView(myColor: .yellow)
let oneView = flipView(myColor: .green)
static func flipView(myColor: UIColor) -> UIView {
let view = UIView()
view.backgroundColor = myColor
return view
}
let zeroLabel: UILabel = {
let lb = UILabel()
lb.text = "Zero 0"
return lb
}()
let oneLabel: UILabel = {
let lb = UILabel()
lb.text = "one 1"
return lb
}()
func setupView(){
zeroView.frame = CGRect(x: 0, y: 0, width: frame.width, height:frame.width/4)
oneView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.width/4)
self.addSubview(oneView)
self.addSubview(zeroView)
zeroLabel.frame = CGRect(x: 20, y: (frame.width/4)/2 - 25, width: self.frame.width - 40, height: 50)
oneLabel.frame = CGRect(x: 20, y:(frame.width/4)/2 - 25, width: self.frame.width - 40, height: 50)
zeroView.addSubview(zeroLabel)
oneView.addSubview(oneLabel)
}
}

TableView background keeps white

I'm having a problem with my parallax effect. I'm having a tableView and a ImageView above the tableView. Now when the user scrolls from the top I want to stretch the image a bit. But the problem is that my tableView keeps having a white background like you can see on the screenshot. So the image isn't visible. The screenshot is taken when the viewcontroller loads and then I just pull down as far as I can go. The tableView has backgroundColor .clear so I don't why it isn't working.
My code:
import UIKit
import PureLayout
class ViewController: UIViewController {
lazy var headerImageView: UIImageView = {
let imageView = UIImageView(forAutoLayout: ())
imageView.image = UIImage(named: "test")
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
lazy var tableView: UITableView = {
let tableView = UITableView(forAutoLayout: ())
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.isOpaque = false
tableView.backgroundColor = .clear
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "default")
tableView.tableFooterView = UIView()
tableView.showsVerticalScrollIndicator = false
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.headerImageView)
self.headerImageView.autoPinEdge(toSuperviewEdge: .left)
self.headerImageView.autoPinEdge(toSuperviewEdge: .right)
self.headerImageView.autoPin(toTopLayoutGuideOf: self, withInset: 0)
self.headerImageView.autoSetDimension(.height, toSize: 100)
self.view.addSubview(self.tableView)
self.tableView.autoPinEdge(toSuperviewEdge: .left)
self.tableView.autoPinEdge(toSuperviewEdge: .right)
self.tableView.autoPinEdge(toSuperviewEdge: .bottom)
self.tableView.autoPinEdge(.top, to: .bottom, of: self.headerImageView)
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "default", for: indexPath)
cell.textLabel?.text = "test"
cell.backgroundColor = .red
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// Parallax functionality
let yOffset = scrollView.contentOffset.y * 0.2
let availableOffset = min(yOffset, 60)
let contentRectYOffset = availableOffset / self.headerImageView.frame.size.height
self.headerImageView.layer.contentsRect = CGRect(x: 0.0, y: contentRectYOffset, width: 1, height: 1)
}
}

UITableView keeps autoscrolling to top

When the user tries scrolling down the table (goes past the keyboard height), it automatically scrolls back to the top of table, leaving the user unable to press any of the keys in the bottoms rows of the table. How do I disable this autoscroll to top? Note this is different from the scrollsToTop property.
import UIKit
class KeyboardViewController: UIInputViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView = UITableView()
let screenSize: CGRect = UIScreen.mainScreen().bounds
let buttonTitles = [
"XX",
"YY"
]
override func viewDidLoad() {
super.viewDidLoad()
let screenWidth = screenSize.width
let screenHeight = screenSize.height
tableView.frame = CGRectMake(0,0,screenWidth,screenHeight - 40)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self,forCellReuseIdentifier: "cell")
self.view.addSubview(tableView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.buttonTitles.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = self.buttonTitles[indexPath.row]
cell.textLabel?.textAlignment = .Center
cell.textLabel?.font = UIFont(name: "Helvetica Neue", size: 14)
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.numberOfLines = 0
cell.backgroundColor = UIColor(red: 176/255, green: 15/255, blue: 15/255, alpha: 1.0)
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = UIEdgeInsetsZero
cell.separatorInset = UIEdgeInsetsZero
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var string = buttonTitles[indexPath.row]
(textDocumentProxy as! UIKeyInput).insertText("\(string)")
}
Move your code except
tableView.delegate = self
tableView.dataSource = self
to viewWillAppear

Resources