uploaded video (7 sec) for describing my problem
i have a textView embed in a tableView cell when we enter something on that textView the textview automatically increases its height according to entered content and also cell increases its size for doing this am using this approach:-
//tableViewCell
/// Custom setter so we can initialise the height of the text view
var textString: String {
get {
return textView?.text ?? ""
}
set {
if let textView = textView {
textView.text = newValue
textViewDidChange(textView)
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Disable scrolling inside the text view so we enlarge to fitted size
textView?.scrollEnabled = false
textView?.delegate = self
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
textView?.becomeFirstResponder()
} else {
textView?.resignFirstResponder()
}
}
}
extension MultiLineTextInputTableViewCell: UITextViewDelegate {
func textViewDidChange(textView: UITextView) {
let size = textView.bounds.size
let newSize = textView.sizeThatFits(CGSize(width: size.width, height: CGFloat.max))
// Resize the cell only when cell's size is changed
if size.height != newSize.height {
UIView.setAnimationsEnabled(false)
tableView?.beginUpdates()
tableView?.endUpdates()
UIView.setAnimationsEnabled(true)
if let thisIndexPath = tableView?.indexPathForCell(self) {
tableView?.scrollToRowAtIndexPath(thisIndexPath, atScrollPosition: .Bottom, animated: false)
}
}
}
here everything is fine but i added a function for Forwarding any content and for this am using this approach :-
forwardNoteAction = UITableViewRowAction(style: .Normal, title: "Forward"){ action, index in
let cell = tableView.cellForRowAtIndexPath(indexPath) as! NotesTableViewCell
if self.searchBar.text == "" {
let object: PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject
let postsObjID = object.objectId!
let query = PFQuery(className: "Notes")
query.fromLocalDatastore()
query.getObjectInBackgroundWithId(postsObjID) {
(objectViewes, error) -> Void in
if error != nil {
print(error)
} else {
self.forwardObject = object
print(self.forwardObject)
//object.pinInBackground()
self.performSegueWithIdentifier("forwardNoteSegue", sender: nil)
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
i am putting the content into a variable self.forwardObject and passing that variable with an segue forwardNoteSegue after passing self.forwardObject am using that content for filling my tableView (which is a form , consist of textViews and TextFields) but when am doing this my textView is not increasing its height according to content which is inside that textView ,
all i want is the textView should increase increase its height when we use "textView.text = copiedContent" same as when we enter anything into the textView manually
please for understanding my problem properly see the uploaded video (link is provided above)
if my question is not understandable than please let me know i'll fix it
thanks
You need to manually call textViewDidChange when you modify the content of you textview programatically.
This is documented in the UITextviewDelegate's description of the method:
The text view calls this method in response to user-initiated changes to the text. This method is not called in response to
programmatically initiated changes.
Related
I am having a problem and have searched all across StackO and did not see a solution.
I have a UITextview extension with TextViewDelegate that I call inside of my VC so that i can have a placeholder label. The problem is i now need to add a func that checks for remaining chars in that same textView which i am able to get to work properly. But i cant grab a label to present it on the VC from that extension. I have been trying delegates but since it is a delegate itself i cant use my normal methods. What is the best route to go about this? Thank You for your help!
Here is the code. The placeholder label code is left out since it will make everything longer and I do not feel its needed for a solution. But I can add if necessary. And i can not move this code straight into VC as i need this extension to stay like this.
extension UITextView: UITextViewDelegate {
/// When the UITextView change, show or hide the label based on if the UITextView is empty or not
public func textViewDidChange(_ textView: UITextView) {
if let placeholderLabel = self.viewWithTag(100) as? UILabel {
placeholderLabel.isHidden = !self.text.isEmpty
}
checkRemainingChars(textView: textView)
}
func checkRemainingChars(textView: UITextView) {
let allowedChars = 140
if let charsInTextField = textView.text?.count {
let charsInLabel = charsInTextField
let remainingChars = charsInLabel
if remainingChars <= allowedChars {
//Need to grab this label
charsLeftLabel.textColor = UIColor.lightGray
}
if remainingChars >= 120 {
//Need to grab this label
charsLeftLabel.textColor = UIColor.orange
}
if remainingChars >= allowedChars {
//Need to grab this label
charsLeftLabel.textColor = UIColor.red
}
//This prints fine
print("Remaining chars is \(remainingChars)/140")
//Need to grab this label
charsLeftLabel.text = String(remainingChars)
}
}
Thanks again.
I have UITableView with about 20 row which each contain a UITextField. The first time I tap in a textfield will open the keyboard and I am ready to edit this textfield. If I tap on the next textfield (notice the keyboard is displayed all the time) the keyboard is still displayed but the blue cursor is not in the new textfield and I cannot enter any text. But if I tap on another textfield again, it works just fine. This behavior occurs alternately, one time it works the other time it doesn't.
The delegate method textFieldShouldBeginEditing(_:) is always called, wether I can edit or not. The delegate method textFieldDidBeginEditing(_:) is only called when editing works.
This is the code for cellForRowAt
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldCell")!
let titleLabel = cell.viewWithTag(1) as! UILabel
let contentTextField = cell.viewWithTag(2) as! FixableTextField
contentTextField.delegate = self
contentTextField.inputAccessoryView = doneToolbar
// Enable/disable editing for text fields
if isEditing {
contentTextField.enableEditing()
} else {
contentTextField.disableEditing()
}
// Present Profile Data
if profileUpdateBuffer != nil {
switch indexPath.row {
case 0:
titleLabel.text = "Count"
contentTextField.text = "\(profileUpdateBuffer!.count)"
contentTextField.purposeID = "count"
contentTextField.keyboardType = .numberPad
case 1:
titleLabel.text = "City"
contentTextField.text = "\(profileUpdateBuffer!.city)"
contentTextField.purposeID = "city"
contentTextField.keyboardType = .default
// ...
case 20:
titleLabel.text = "Name"
contentTextField.text = "\(profileUpdateBuffer!.name)"
contentTextField.purposeID = "name"
contentTextField.keyboardType = .default
default:
titleLabel.text = ""
contentTextField.text = ""
}
return cell
}
// No data available -> show info in first row
else {
if indexPath.row == 0 {
titleLabel.text = "No data"
contentTextField.text = "No data"
}
else {
titleLabel.text = ""
contentTextField.text = ""
}
return cell
}
}
The enableEditing() and disableEditing() method are from class FixableTextField. I can see that the textfields are always enabled because I can see the textfield border
// Extract from FixableTextField class
func enableEditing() {
self.isEnabled = true
self.borderStyle = .roundedRect
}
func disableEditing() {
self.isEnabled = false
self.borderStyle = .none
}
Code for the UITextField
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
// Delete empty field indicator "-"
if textField.text == "-" {
textField.text = ""
}
//Move profileTable's contentView to correct position
if textField is FixableTextField {
let path = IndexPath(row: rowMap[(textField as! FixableTextField).purposeID]!, section: 0)
moveContentViewUp(indexPath: path)
}
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
// Save new value to profileUpdateBuffer
do {
try self.profileUpdateBuffer?.setProperty(value: textField.text!, key: (textField as! FixableTextField).purposeID)
} catch ProfileError.PropertySettingWrongType {
let falseInputAlert = UIAlertController(title: "False Input", message: "The input for this field is not valid.", preferredStyle: .alert)
falseInputAlert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(falseInputAlert, animated: true, completion: nil)
} catch {
print("Error when trying to set property for profileUpdateBuffer in ProfileViewController")
}
// Display new data in table
profileTable.reloadData()
}
Extract from setProperty method which is from class ProfileData. profileUpdateBuffer is of type ProfileData
func setProperty(value:String, key:String) throws {
switch key {
case "count":
count = value
case "city":
count = value
// ...
case "name":
name = value
default:
throw ProfileError.PropertySettingWrongType
}
}
I've made a small program to mimic the behavior you describe.
It seems the issue is caused by table view data reloading at the end of your textFieldDidEndEditing(_:):
func textFieldDidEndEditing(_ textField: UITextField) {
// Save new value to profileUpdateBuffer
do {
try self.profileUpdateBuffer?.setProperty(value: textField.text!, key: (textField as! FixableTextField).purposeID)
} catch ProfileError.PropertySettingWrongType {
let falseInputAlert = UIAlertController(title: "False Input", message: "The input for this field is not valid.", preferredStyle: .alert)
falseInputAlert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(falseInputAlert, animated: true, completion: nil)
} catch {
print("Error when trying to set property for profileUpdateBuffer in ProfileViewController")
}
// Display new data in table
profileTable.reloadData()
}
Try removing profileTable.reloadData() for the sake of experiment to confirm the root cause of the problem (yes, your other cells will not be updated).
One way to solve this is by utilizing direct cell updates on visibleCells in textFieldDidEndEditing(_:). I see profileUpdateBuffer? is your data model. Just update your cell's titleLabel and textField properties manually from your model if they are in visible cells property of the table view.
If you want to size the cells accordingly, use AutoLayout and UITableViewAutomaticDimension for table view row height combined with beginUpdates()/endUpdates() calls.
For more details on how to achieve direct cell manipulation and/or dynamic cell size update without loosing the keyboard focus check the accepted answer on this question I've already answered.
Hope this will help!
I believe the problem is that you call profileTable.reloadData()... You should probably only reload one cell. Perhaps textFieldDidEndEditing(:) gets called with the old TextField as a parameter, followed by textFieldShouldBeginEditing(:) for the new TextField. The problem is that you refresh all the cells at the end of textFieldDidEndEditing(:), which means the TextField passed by the system as a parameter to textFieldShouldBeginEditing(:) may not necessary be the same one that the corresponding cell contains... It may be that those new key-strokes get sent to a TextField belonging to a cell that is in the Queue of reusable cells, i.e. not visible, but still existing somewhere in memory.
I'm currently battling with the keyboard covering some textField issue on my Swift based iPhone app.
This image shows the primary problem (top three images show the problem, bottom three are what it should be doing):
When the textField in the tableViewCell is edited I want to move the whole tableview and navigation bar up. I can do this with the code below (snippets taken from the viewController):
var tableViewShiftedUp = false
...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! QuantityTableViewCell
let componentLocationQuantity = tableViewData[indexPath.row]
if let locationString = componentLocationQuantity.location.valueForKey("location_name") as? String {
cell.setCellContents(locationString, quantity: componentLocationQuantity.quantity.floatValue)
cell.quantityLabel.delegate = self
}
//get stock level related to current build rate and lead time (good - green, warning - orange, urgent - red)
let status = model.determineStockLevelStatus(component)
cell.setQuantityLabelBackgroundStatusColor(status)
if editingMode == true {
cell.makeQuantityEditable()
}
//add control event to detect text change
cell.quantityLabel.addTarget(self, action: #selector(quantityCellTextChanged(_:)), forControlEvents: UIControlEvents.EditingChanged)
cell.quantityLabel.addTarget(self, action: #selector(quantityCellSelected(_:)), forControlEvents: UIControlEvents.EditingDidBegin)
return cell
}
...
//MARK: - UITextfield delegate
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
if tableViewShiftedUp == true {
moveTable()
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func quantityCellSelected(textField: UITextField){
if tableViewShiftedUp == false {
moveTable()
}
//check table was moved
print(tableView.frame.origin.y)
}
func hideKeyboard(){
self.view.endEditing(true)
if tableViewShiftedUp == true {
moveTable()
}
}
func moveTable(){
if tableViewShiftedUp == true {
animateTableViewMoving(false, moveValue: 250)
animateNavigationBarMoving(false, moveValue: 250)
tableViewShiftedUp = false
} else {
animateTableViewMoving(true, moveValue: 250)
animateNavigationBarMoving(true, moveValue: 250)
tableViewShiftedUp = true
}
}
// moving the tableView
func animateTableViewMoving (up:Bool, moveValue :CGFloat){
let movementDuration:NSTimeInterval = 0.0
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.tableView.frame = CGRectOffset(self.tableView.frame, 0, movement)
UIView.commitAnimations()
}
// moving the navigationBar
func animateNavigationBarMoving (up:Bool, moveValue :CGFloat){
let movementDuration:NSTimeInterval = 0.0
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.midNavigationBar.frame = CGRectOffset(self.midNavigationBar.frame, 0, movement)
UIView.commitAnimations()
}
And it works fine when moving directly to the textField in the tableView. However, when I am already editing a textField outside the tableView the shift up doesn't happen and so the shifting toggle gets out of sync.
I've printed the tableView frame origin:
//check table was moved
print(tableView.frame.origin.y)
so I can see what the tableView is set to and on that first move from textField outside the tableView to textField inside the tableView, this property is what I would expect it to be 134, however it's still at 384 on the screen which it prints the next time it's called.
The problem doesn't occur when moving within cells in the tableView.
It feels like I've got some kind of race condition problem or I'm missing some delegate method being called that is throwing everything off when transitioning from one cell to the next.
Help would be great.
Check out this library: https://github.com/michaeltyson/TPKeyboardAvoiding.
Designed so that it gets the keyboard out of the way of text fields.
When you use autolayout you cannot resize frame directly like you doing, you must work with constraints (you can create IBOutlets for constraints created in IB or add new ones, then send layoutIfNeeded to your view from within an animation block).
You can follow official Apple instructions:
About Auto Layout and Layout Constraints
Animating Layer Content
I am having some serious trouble getting my multiline label to show all of its lines. Often, the last line of the label simply does not appear, but it is apparent that the dynamically calculated cell height has taken in to account that it should have appeared, leaving around the appropriate amount of white space left over in my cell.
The affected label can display 1-7 lines depending on the data. I have played around with many various constraints to try and get it to display but regardless of what is on the last line, it just won't display.
The weird thing is, sometimes it will display when I segue in to the VC, but then when I use the segmented controller inside the VC to display different data and then go back again, the last line will again not display. The opposite happens frequently too (last line of label cutting off when I segue in to the VC, but then using the segmented controller inside the VC to change the displayed data and then go back, it will then display fine).
Things I have ensured: The label is set to word wrap, has line count of 0, has a height greater than or equal to the height of one of it's lines, its resistance and vertical content hugging is set to the highest of anything in the cell, and the width is set appropriately.
The below code is how I determine how many lines the label will have:
let descString = NSMutableAttributedString()
let bountyStart = NSMutableAttributedString(string: "Bounty: ", attributes: [NSFontAttributeName : UIFont.boldSystemFontOfSize(15)])
let bountyDesc = NSMutableAttributedString(string: bounty.description)
descString.appendAttributedString(bountyStart)
descString.appendAttributedString(bountyDesc)
let bLine = NSMutableAttributedString(string: "\n\n", attributes: [NSFontAttributeName : UIFont.systemFontOfSize(2)])
descString.appendAttributedString(bLine)
if !(bounty.turtles == 0.0){
let turtleStart = NSMutableAttributedString(string: "Your turtle count: ")
let turtleAmount = NSMutableAttributedString(string: bounty.turtleCount.description)
descString.appendAttributedString(turtleStart)
descString.appendAttributedString(turtleAmount)
}
descriptionLabel.attributedText = descString
In the screen shot below, you can see that the height of the cell is being calculated appropriately but for some reason, the last line of the label just refuses to show. It should appear after the "is for noobs" line. I've manipulated the white space to appear after the line instead of elsewhere by setting the problem labels bottom to constraint to be greater than or equal, and all other top to bottom constraints as equal to.
Constraints of the problem label:
I've been stumped for quite a while on this one, and I'm starting to think it's not the constraints I've set but something much deeper. All though I would love to be proven wrong.
Here is my VC code.
import UIKit
class TrendingVC: UIViewController, UITableViewDataSource, UITableViewDelegate{
#IBOutlet weak var menubtn:UIBarButtonItem!
#IBOutlet var trendingTableView:UITableView!
var trendingToggle:Int = 0
let nwt = NWTrending()
let appUserId = NSUserDefaults.standardUserDefaults().stringForKey("UserId") ?? "1" //#TODO: remove ?? 1
var bountyArr: [Bounty] = []
var compArr: [Completion] = []
var peopleArr: [Person] = []
var userId: String = "0"
var username: String = ""
let bountyCellIdentifier = "BountyCellNew"
let personCellIdentifier = "PersonCell"
let completedCellIdentifier = "TrendingCompletedImageCell"
#IBAction func toggleTrending(sender:UISegmentedControl){
switch sender.selectedSegmentIndex{
case 0:
//loads the bounties on segmented control tab
trendingToggle=0
nwt.getTrendingBounties(appUserId, position: 0){(bountyArr, err) in //#TODO: change pos
self.bountyArr = bountyArr as [Bounty]
self.reloadTableViewContent()
}
case 1:
trendingToggle=1
nwt.getTrendingCompletions(appUserId, position: 0){(compArr, err) in
self.compArr = compArr as [Completion]
self.reloadTableViewContent()
}
case 2:
trendingToggle=2
nwt.getTrendingPeople(appUserId, position: 0){(peopleArr, err) in
self.peopleArr = peopleArr as [Person]
self.reloadTableViewContent()
}
default:
break
}
//reloadTableViewContent()
}
override func viewDidLoad() {
super.viewDidLoad()
trendingTableView.estimatedRowHeight = 300.0
trendingTableView.rowHeight = UITableViewAutomaticDimension
/******* Kyle Inserted *******/
//for followers and following back button text, you set it here for when you segue into that section
let backItem = UIBarButtonItem(title: " ", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backItem
/******* END Kyle Inserted *******/
trendingTableView.allowsSelection = false;
trendingTableView.delegate = self
trendingTableView.dataSource = self
//sidebar code
if self.revealViewController() != nil {
menubtn.target = self.revealViewController()
menubtn.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
//loads the bounty on segue
nwt.getTrendingBounties(appUserId, position: 0){(bountyArr, err) in
self.bountyArr = bountyArr as [Bounty]
self.reloadTableViewContent()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//deselectAllRows()
}
func deselectAllRows() {
if let selectedRows = trendingTableView.indexPathsForSelectedRows() as? [NSIndexPath] {
for indexPath in selectedRows {
trendingTableView.deselectRowAtIndexPath(indexPath, animated: false)
}
}
}
func reloadTableViewContent() {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.trendingTableView.reloadData()
println("reloading table view content")
self.trendingTableView.scrollRectToVisible(CGRectMake(0, 0, 1, 1), animated: false)
})
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(trendingTableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if trendingToggle == 0{
return bountyArr.count
}
else if trendingToggle == 1{
return compArr.count
}
else {
return peopleArr.count
}
}
func tableView(trendingTableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if trendingToggle == 0{
return bountyCellAtIndexPath(indexPath)
}
else if trendingToggle == 1{
return completedCellAtIndexPath(indexPath)
}
else{
return personCellAtIndexPath(indexPath)
}
}
//calls method to set and display each trending bounty cell
func bountyCellAtIndexPath(indexPath:NSIndexPath) -> BountyCellNew {
let cell = trendingTableView.dequeueReusableCellWithIdentifier(bountyCellIdentifier) as! BountyCellNew
var bounty = bountyArr[indexPath.row]
cell.setBountyCellTrending(bounty)
return cell
}
func completedCellAtIndexPath(indexPath:NSIndexPath) -> CompletedCell{
let cell = trendingTableView.dequeueReusableCellWithIdentifier(completedCellIdentifier) as! CompletedCell
var comp = compArr[indexPath.row]
cell.setTrendingCompletedCell(comp)
return cell
}
func personCellAtIndexPath(indexPath:NSIndexPath) -> PersonCell{
let cell = trendingTableView.dequeueReusableCellWithIdentifier(personCellIdentifier) as! PersonCell
var peop = peopleArr[indexPath.row]
cell.setTrendingPeopleCell(peop)
return cell
}
}
Unable to comment due to rep low.
This seems like a IB thing, very likely constraints.
Make sure that any component's top constraint placed under this multiline UILabel is set to the bottom of said UILabel.
For example, in this project of mine, both the TitleView and TimeAndDetailsView contain UILabels that span multiplelines. In order to allow autolayout to properly space things all constraints need to be in order, also notice how the top constraint of TimeAndDetails is the bottom of TitleView
Edit note:
Before you tableView.reloadData() type the following 2 lines, or if uncertain, put it inside viewDidLoad
tableView.estimatedRowHeight = 60 //Type your cell estimated height
tableView.rowHeight = UITableViewAutomaticDimensionhere
Went to sleep last night, ok so I decided to add your code to my details label from the storyboards picture I had posted before, and it seems to have displayed just fine. I have a few questions and pointers below.
let descString = NSMutableAttributedString()
let bountyStart = NSMutableAttributedString(string: "Bounty: ", attributes: [NSFontAttributeName : UIFont.boldSystemFontOfSize(15)])
let bountyDesc = NSMutableAttributedString(string: "this would be 'bounty.description and is set to size 40", attributes: [NSFontAttributeName : UIFont.boldSystemFontOfSize(40)])
descString.appendAttributedString(bountyStart)
descString.appendAttributedString(bountyDesc)
let bLine = NSMutableAttributedString(string: "\n\n", attributes: [NSFontAttributeName : UIFont.systemFontOfSize(10)])
descString.appendAttributedString(bLine)
let turtleStart = NSMutableAttributedString(string: "Your turtle count: ")
let turtleAmount = NSMutableAttributedString(string: "random number 1234 goes here")
descString.appendAttributedString(turtleStart)
descString.appendAttributedString(turtleAmount)
detailsLabel.attributedText = descString
Sadly, this is in a scrollview and not in a cell, so there is the first difference. My first question; is your descriptionLabel.attributedText supposed to display different fontscolors or fonttypes/sizes?, if not then I would say to just use descriptionLabel.text instead of descriptionLabel.attributedText.
Now the fact that there is white space but nothing showing us makes me wonder if bounty.turtleCount.description was previously set to color white somewhere else, or you are simply seeing the newlines you added \n\n and nothing is there because if !(bounty.turtles == 0.0) doesnt execute. Are you sure the that if statement is executed? place a breakpoint and follow along to make sure the values are appended to descString
If this is all correct, then my guess would still be on constraints.
Could you elaborate on, quote from you; "sometimes it will display when I segue in to the VC, but then when I use the segmented controller inside the VC to display different data and then go back again, the last line will again not display." what are you doing different in the seg control when loading the values and reloading the tableview that makes it not display, and under what conditions does it work properly when you segue.
I updated xcode and now this doesn't happen anymore.
I have UITableView with CustomCell. I want to rotate record image when a cell fully visible or visible more than half at least.
This code block in CustomTableViewCell.swift
override func setSelected(selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
RotateImage()
}
The problem is that image is starting rotate immediately custom cell appeared like image below.
Sample Image:
There are 2 cells. First one is fully visible and rotating. And second one is partially visible / loaded but its also rotating.
Is it possible to check visibility in setSelected code block or need to check with UITableView functions?
The result should be like that:
override func setSelected(selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
if fullyVisible == true
{
RotateImage()
}
}
Thanks.
If you want more control for the behavior of cells based on their visibility withing the bounds of your screen, you could use UIScrollViewDelegate functions
such as:
optional func scrollViewDidScroll(_ scrollView: UIScrollView)
Get an array of the tableView's visible cells.
you can check the bounds of each cell to see if it is on screen
Check if the cell's record is spinning and if not start the rotation.
I did something similar in one of my projects:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let visibleArea = scrollView.contentOffset.y + scrollView.height
for cell in tableView.visibleCells {
guard let propertyGraphCell = cell as? PropertyGraphCell else { continue }
if cell.frame.midY <= visibleArea, let indexPath = tableView.indexPath(for: cell) {
switch visibleRows[indexPath.row] {
case .daysOnMarket:
if daysOnMarketAnimated {
propertyGraphCell.drawLine(animated: true)
daysOnMarketAnimated = false
}
case .priceTrend:
if priceTrendAnimated {
propertyGraphCell.drawLine(animated: true)
priceTrendAnimated = false
}
case .vendorDiscount:
if vendorDiscountAnimated {
propertyGraphCell.drawLine(animated: true)
vendorDiscountAnimated = false
}
case .marketInsights:
assert(false, "cell animation not supported")
}
}
}
}