I am programmatically adding a UITableView as a subview of a view that uses UIView.animateWithDuration to expand the view when a button is clicked from a single point to a full window. Basically, a box that starts as a point and expands to full size with an animation. I am having difficulties getting the table to populate with cells. At first, a cell was being created, but would disappear after quickly after the animation completed, after playing around with it, I have gotten the cell to remain after the animation is complete, but now the cell disappears when I tap on it. I don't understand what is going on here. Can someone please help?
Here is my code. Note, I have removed what I believe to be irrelevant to this problem to make the code easier to read.
class PokerLogSelectionView: UIViewController {
let logSelectionTableViewController = LogSelectionTableViewController()
let logSelectionTableView = UITableView()
// Irrelevant class variables removed
init(btn : PokerLogSelectionButton){
// Irrelevant view initialization code removed
// Display the subviews
self.displayLogListScrollView()
}
func displayLogListScrollView() {
// Frame is set to (0,0,0,0)
let frame = CGRect(x: self.subviewClosed, y: self.subviewClosed, width: self.subviewClosed, height: self.subviewClosed)
logSelectionTableView.delegate = self.logSelectionTableViewController
logSelectionTableView.dataSource = self.logSelectionTableViewController
// Set the frame of the table view
logSelectionTableView.frame = frame
// Give it rounded edges
logSelectionTableView.layer.cornerRadius = 10
// Remove the cell divider lines
logSelectionTableView.separatorStyle = UITableViewCellSeparatorStyle.None
logSelectionTableView.backgroundColor = logSelectionViewContentScrollViewColor
self.view.addSubview(logSelectionTableView)
//self.logSelectionTableView.reloadData()
//self.addChildViewController(logSelectionTableViewController)
}
override func viewDidAppear(animated: Bool) {
// Create animation
let timeInterval : NSTimeInterval = 0.5
let delay : NSTimeInterval = 0
UIView.animateWithDuration(timeInterval, delay: delay, options: UIViewAnimationOptions.CurveEaseOut, animations: {
// Irrelevant code removed
// Set the size and position of the view and subviews after the animation is complete
self.view.frame = CGRect(x: self.frameXopen, y: self.frameYopen, width: self.frameWopen, height: self.frameHopen)
self.logSelectionTableView.frame = CGRect(x: self.subviewXopen, y: self.svYopen, width: self.subviewWopen, height: self.svHopen)
}, completion: { finished in
self.addChildViewController(self.logSelectionTableViewController)
})
}
}
class LogSelectionTableViewController : UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(LogSelectionCell.self, forCellReuseIdentifier: "logCell")
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pokerLibrary.logNames.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 20
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Selected row: \(indexPath.row)")
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell : LogSelectionCell = self.tableView.dequeueReusableCellWithIdentifier("logCell") as? LogSelectionCell {
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.textLabel!.text = pokerLibrary.logNames[indexPath.row].name
return cell
}
fatalError("Could not dequeue cell of type 'LogSelectionCell'")
}
}
Note: I can see the tableview after the animation is complete. The color is different than the view in the background view and the tableview does not disappear, just the cell. I expect there to be 1 cell, and I have printed out the number of rows in section 0 and it always returns 1.
Thanks for the help!
Edit:
Here is a screenshot of the view hierarchy before the cell disappears.
Here is a screenshot of the view hierarchy after I tap the cell and it disappears.
I overrode the touchesBegan method in my custom cell and did not call its superclass method. This stopped the cell from disappearing when I tap it, but it still disappears when I scroll the tableView.
Related
I have table view. Inside cell I have method that animates view inside cell.
func animateCell() {
UIView.animate(withDuration: 0.4, animations: { [weak self] in
self?.quantityBackround.transform = CGAffineTransform(scaleX: 25, y: 25)
}) { [weak self] _ in
UIView.animate(withDuration: 0.1) {
self?.quantityBackround.transform = CGAffineTransform.identity
}
}
}
Also I have prepareForReuse()
override func prepareForReuse() {
quantityBackround.transform = CGAffineTransform.identity
}
The animation must work only for last cell when array of datasource changes and I do this in property observer like this (fires when something is being added to array)
guard let cell = checkTableView.cellForRow(at: IndexPath(row: viewModel.checkManager.check.count - 1, section: 0)) as? CheckItemTableViewCell else { return }
cell.animateCell()
All of this works fine.
One problem, is that I encounter is that when tableView is reloaded, all background views in all cells expand from zero size to its initial. Last cell animates ok.
I think that i miss something in prepareForReuse and because of this i see this glitch of inreasing from zero to initial size.
How to fix it ?
You need to implement this method of UITableViewDelegate
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//here check if your this cell is the last one, something like this
if (indexPath.row == yourDataSourceArray.count - 1)
{
if let customCell = cell as? CheckItemTableViewCell{
customCell.animateCell()
}
}
}
Hope this helps
I can't see suggestions when typing.. i have tableview cell and textfield in it.
I'm using MPGTextField library, swift version(swift 2 supported).
Any solution for this?
Code:
#IBOutlet weak var articleField: MPGTextField_Swift!
override func viewDidLoad() {
super.viewDidLoad()
articleField.mDelegate = self
}
func dataForPopoverInTextField(textfield: MPGTextField_Swift) -> [Dictionary<String, AnyObject>] {
return articles
}
func textFieldShouldSelect(textField: MPGTextField_Swift) -> Bool{
return true
}
func textFieldDidEndEditing(textField: MPGTextField_Swift, withSelection data: Dictionary<String,AnyObject>){
print(data["CustomObject"])
}
In the MPGTextField-Swift.swift you'll find a function provideSuggestions()
In this function you'll find a line
self.superview!.addSubview(tableViewController!.tableView)
Replace this line with
//BUG FIX - SHOW ON TOP
//self.superview!.addSubview(tableViewController!.tableView)
let aView = tableViewController!.tableView
var frame = aView.frame
frame.origin = self.superview!.convertPoint(frame.origin, toView: nil)
aView.frame = frame
self.window!.addSubview(aView)
////
I've forked MPGTextField repository, made necessary changes for demo purpose.
You can find my repo at https://github.com/rishi420/MPGTextField
Note: This repo needs Xcode 7.1.1 to compile. Feel free to contribute. :-]
I can't really tell what's going on. Is the autocomplete box showing but just cut off at the bottom of the tableViewCell? If so, try setting clipsToBounds to false on the tableViewCell, and maybe even its content view too.
Touch events are not by default recognized for areas outside of a view's frame. To route the taps to the suggestion, you'll have to subclass the tableViewCell and override hitTest
A solution for this would be set the cell height when the cell is selected:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.beginUpdates()
self.tableView.endUpdates()
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if tableView.indexPathForSelectedRow == indexPath {
return self.selectedCellHeight
}
return self.unSelectedCellHeight
}
You only have to set the unselectedCellHeight and the selectedCellHeight
The beginUpdates() and endUpdates() will update the cell height and animate it.
I am new to swift, I am trying to have a UITableView and the cells will be animated to appear one by one. How can I do that? Also, if the newly appeared row of cell not on the screen (hiding below the table). How can I move the table up when each cell appear?
var tableData1: [String] = ["1", "2", "3", "4", "5", "6", "7"]
override func viewWillAppear(animated: Bool) {
tableView.scrollEnabled=false
tableView.alpha=0.0
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "animateTable", userInfo: nil, repeats: false)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tableData1.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:TblCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! TblCell
cell.lblCarName.textAlignment = NSTextAlignment.Justified;
return cell
}
func animateTable() {
//what should be the code?//
}
Step-1
In your cellForRowAtIndexPath method where initialize your cell, hide it like that;
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: TblCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TblCell
cell.continueLabel.textAlignment = .justified
cell.contentView.alpha = 0
return cell
}
Step-2
Let's make fade animation. UITableViewDelegate has willDisplayCell method which is able to detect that when you scroll to top or bottom, first cell will display on the window.
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
UIView.animate(withDuration: 0.8, animations: {
cell.contentView.alpha = 1
})
}
Your fade animation is on the progress. The most important thing is that you can not setup your cell's alpha directly in runtime because iOS is doing some special internal handling with the cell as part of your UITableView and ignores your setup. So if you setup your cell's contentView, everything's gonna be fine.
In the UITableView, the rows are prepared automatically for you when they get to be in your "range vision". I'm assuming you are, at least not initially, being able to scroll the tableView, so we would scroll it programmatically making the rows appear as it goes. How are we doing that? Actually UITableView has a method that let us scroll it to a specific row:
scrollToRowAtIndexPath(indexPath : NSIndexPath, atScrollPosition : UITableViewScrollPosition, animated : Bool);
I'm too tired to write the code, so I'm going to try to explain. First, for every cell you set alpha to 0, as soon as they get loaded (cellForRowAtIndexPath).
Then let's suppose our screen fits the 5 first rows. You are going to animate their alphas sequentially (using UIView.animateWithDuration ) until the fifth one (index 4), then you are going to scrollToRowAtIndexPath passing NSIndexPath using 5, then 6,... until the rest of them (using scrollPosition = .Bottom). And for each of them, you would animate as soon as they get loaded. Just remember to put some time between this interactions. (animate first, run NSTimer to the second, and it goes on). And the boolean animated should be true of course.
To appear each visible cell one by one, you can do it by playing with alpha and duration value.
extension UITableView {
func fadeVisibleCells() {
var delayDuration: TimeInterval = 0.0
for cell in visibleCells {
cell.alpha = 0.0
UIView.animate(withDuration: delayDuration) {
cell.alpha = 1.0
}
delayCounter += 0.30
}
}
}
Here is some code which can get you started. In my COBezierTableView
I subclassed UITableView and override the layoutSubviewsmethod. In there you can manipulate the cells according to their relative position in the view. In this example I fade them out in the bottom.
import UIKit
public class MyCustomTableView: UITableView {
// MARK: - Layout
public override func layoutSubviews() {
super.layoutSubviews()
let indexpaths = indexPathsForVisibleRows!
let totalVisibleCells = indexpaths.count - 1
if totalVisibleCells <= 0 { return }
for index in 0...totalVisibleCells {
let indexPath = indexpaths[index]
if let cell = cellForRowAtIndexPath(indexPath) {
if let superView = superview {
let point = convertPoint(cell.frame.origin, toView:superView)
let pointScale = point.y / CGFloat(superView.bounds.size.height)
cell.contentView.alpha = 1 - pointScale
}
}
}
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell .alpha = 1.0
let transform = CATransform3DTranslate(CATransform3DIdentity, 0, 3000, 1200)
//let transform = CATransform3DTranslate(CATransform3DIdentity, 250, 0, 1250)
//let transform = CATransform3DTranslate(CATransform3DIdentity, 250, 1250, 0)
// let transform = CATransform3DTranslate(CATransform3DIdentity, -250, 300, 120)
cell.layer.transform = transform
UIView.animate(withDuration: 1.0) {
cell.alpha = 1.0
cell.layer.transform = CATransform3DIdentity
cell.layer.transform = CATransform3DIdentity
}
}
I think this method will be a great solution.
Set all cell alpha to 0
animate them in tableView(_:,willDisplay:,forRowAt:)
set a delay for every indexPath.row
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.alpha = 0
UIView.animate(withDuration: 0.5, delay: 0.05 * Double(indexPath.row), animations: {
cell.alpha = 1
})
}
I have a tableview need to be updated very second. The code are as following. I design the headerview to have a dropdown function, when the header tap the rest are displayed. The code will crashes when I am trying to tap the header, the thread stops, xcode is not giving any hint on how and why.
func didListOfBLEDevicesUpdate(newDevice: BLEDevice)
{
println("receivedDevice from scanner every second: \(newDevice.deviceName)")
self.deviceTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return BLEDevice.listOfDevices.items.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1;
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return BLEDevice.listOfDevices.items[section].deviceName
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if(IsExpandedMode[indexPath.section] == true){
return 400
}
return 70;
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))
headerView.backgroundColor = UIColor.grayColor()
headerView.tag = section
let headerString = UILabel(frame: CGRect(x: 10, y: 10, width: tableView.frame.size.width-10, height: 30)) as UILabel
headerString.text = BLEDevice.listOfDevices.items[section].deviceName
headerView .addSubview(headerString)
let headerTapped = UITapGestureRecognizer (target: self, action:"sectionHeaderTapped:")
headerView .addGestureRecognizer(headerTapped)
return headerView
}
func sectionHeaderTapped(recognizer: UITapGestureRecognizer) {
println("Tapping working")
println(recognizer.view?.tag)
var indexPath : NSIndexPath = NSIndexPath(forRow: 0, inSection:(recognizer.view?.tag as Int!)!)
if (indexPath.row == 0) {
var collapsed = self.IsExpandedMode [indexPath.section]
collapsed = !collapsed;
self.IsExpandedMode[indexPath.section] = collapsed
//reload specific section animated
var range = NSMakeRange(indexPath.section, 1)
var sectionToReload = NSIndexSet(indexesInRange: range)
self.deviceTableView.reloadSections(sectionToReload, withRowAnimation:UITableViewRowAnimation.Fade)
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : DeviceTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! DeviceTableViewCell
let row = indexPath.row
cell.deviceName!.text = BLEDevice.listOfDevices.items[row].deviceName
cell.connectionStatus.text = BLEDevice.listOfDevices.items[row].connectionStatus
cell.deviceSignalStrengthen.text = BLEDevice.listOfDevices.items[row].RSSI
cell.manufacturerData.text = BLEDevice.listOfDevices.items[row].advertisementPackage.cBAdvertisementDataManufacturerData
cell.serviceUUID.text = BLEDevice.listOfDevices.items[row].advertisementPackage.cBAdvertisementDataServiceUUIDs
cell.serviceData.text = DataConvertHelper.getNSDictionary(BLEDevice.listOfDevices.items[row].advertisementPackage.cBAdvertisementDataServiceData)
cell.TxPowerLevel.text = BLEDevice.listOfDevices.items[row].advertisementPackage.cBAdvertisementDataTxPowerLevel
cell.IsConnectable.text = DataConvertHelper.getBool(BLEDevice.listOfDevices.items[row].advertisementPackage.cBAdvertisementDataIsConnectable)
cell.solicitedServiceUUID.text = BLEDevice.listOfDevices.items[row].advertisementPackage.cBAdvertisementDataSolicitedServiceUUIDs
cell.shortenedLocalName.text = BLEDevice.listOfDevices.items[row].advertisementPackage.cBAdvertisementDataLocalName
return cell
}
Use reload sections and reload rows rather than reloading data
The method you have used to handle the table seems to be rather complex. An alternative would be as follows:
1) Assumption from you code is that each device is associated with a section. As noted in the comments, your cellForRorAtIndexPath method seems to be using [row] to index your data model, but the model is based on [section] as you always return the number of rows as 1 for every section and the number of sections is the number of devices.
2) Rather than using a header view for each section and having to add gesture recognizers, simply create a custom cell to represent the device and make this row 0 of the section.
3) So each device is associated with a section, and row 0 of each section is the header information cell, NOT a header view. Make the header view nil. You can use a header height to leave a gap between sections.
4) Add code to detect selection of cells. When the cell row is 0, its the header cell. If the device is collapsed, set it to be expanded and vice versa and reload the section.
5) Make a new custom cell for you dropdown information. this will be row 1 of any section which is showing information.
6) Update your number of rows in section to return 2 if expanded, or 1 if collapsed.
7) Update cellForRowAtIndexPath to return the header cell for row 0 and the detail cell for row 1. Make sure to fix the [row] indexing to be [section] indexing.
This gives you a table of device header cells, which when clicked insert a detail cell below and when clicked again remove it and no gesture recognizers needed.
You need to make sure that your data model updates are working correctly. Seems from your errors that you are not updating the data model properly: in particular removal of devices.
I'm trying to write a check in App, where after the user enters information on the first view the view changes to a tableView of meetings. Currently I'm facing two issues; the first issue is the cell scroll past the header and under the status bar, How do I fix this? the second issue is scrolling down pulls the header with it, is there a way to change this?
I looked online a bit, and some people suggested using a Nav Controller and putting a UItable view inside of it. I'm trying to avoid the StoryBoard so I'm wondering how do I do this using code.
Here is my code so far
class MeetingsViewController: UITableViewController, UITableViewDelegate, {
#IBOutlet var meetingsView : UITableView
var meetings = []
override func viewDidLoad() {
super.viewDidLoad()
title = "Meetings"
![enter image description here][1]tableView.registerClass(MeetingCell.self, forCellReuseIdentifier: "cell")
let edgeInsets = UIEdgeInsetsMake(20, 0, 0, 0)
self.tableView.contentInset = edgeInsets
self.tableView.scrollIndicatorInsets = edgeInsets
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String!
{
return "Meetings"
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let cell = tableView!.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as MeetingCell
if let path = indexPath {
//let entry = news[path.row] as NSDictionary
cell.text = "Meeting Name "
cell.detailTextLabel.text = "Time "
}
return cell
}
}
Try this in your controller's init():
let height = UIApplication.sharedApplication().statusBarFrame.size.height
let insets = UIEdgeInsets(top: height, left: 0, bottom: 0, right: 0)
self.tableView.contentInset = insets
self.tableView.scrollIndicatorInsets = insets