编辑文本后如何重置tableview的高度

Posted

技术标签:

【中文标题】编辑文本后如何重置tableview的高度【英文标题】:How do I reset tableview's height after editing text 【发布时间】:2016-07-02 15:17:28 【问题描述】:

您好,我正在尝试在编辑文本后重置 tableview 的高度..

步骤 1. Tab 输入文本视图

第 2 步。在 1 行上输入注释消息..(例如 2 行,3 行..)

第 3 步。点击发送按钮

步骤 4. 重置 UI

我的问题是..当我将评论输入为 1 行时...效果很好..

但我确实输入了评论 2 行或更多...然后 tableview 的高度没有重置...

你能帮帮我吗?

import UIKit
import Parse

var commentUUID = [String]()
var commentOwner = [String]()

class CommentViewController: UIViewController, UITextViewDelegate, UITableViewDelegate, UITableViewDataSource

    //UI Objects
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var commentTextView: UITextView!
    @IBOutlet weak var sendButton: UIButton!
    @IBOutlet weak var bottomConstraint: NSLayoutConstraint!
    var refresher = UIRefreshControl()

    //values for reseting UI to default
    var tableViewHeight : CGFloat = 0
    var commentY : CGFloat = 0
    var commentHeight : CGFloat = 0
    var tableDiff : CGFloat = 0

    //arryas to hold server data
    var usernameArray = [String]()
    var profileArray = [PFFile]()
    var commentArray = [String]()
    var dateArray = [NSDate?]()


    //variable to hold keyboard frame
    var keyboard = CGRect()

    //page size
    var page : Int32 = 15

    override func viewDidLoad() 

        super.viewDidLoad()

        tableView.backgroundColor = UIColor(red: 242.0 / 255.0, green: 242.0 / 255.0, blue: 242.0 / 255.0, alpha: 1)


        //title at the top
        self.navigationItem.title = "COMMENTS"
        self.navigationItem.hidesBackButton = true
//        let backButton = UIBarButtonItem(title: "back", style: .Plain, target: self, action: #selector(CommentViewController.back(_:)))
      let backButton = UIBarButtonItem(image: UIImage(named: "backBtn"), style: .Plain, target: self, action: #selector(CommentViewController.back(_:)))




        self.navigationItem.leftBarButtonItem=backButton


        //swipe to go back
        let backSwipe = UISwipeGestureRecognizer(target: self, action: #selector(CommentViewController.back(_:)))
        backSwipe.direction=UISwipeGestureRecognizerDirection.Right
        self.view.addGestureRecognizer(backSwipe)

        // catch notification if the keyboard is shown or hidden
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CommentViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)



        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CommentViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)

        //disable button from the beginning
        sendButton.enabled = false

        loadComments()

        //call function
        alignment()

    


    //func loading when keyboard is shown
    func keyboardWillShow(notification : NSNotification)

        //define keyboard frame size
        keyboard = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey]!.CGRectValue)!

        //move UI up
        UIView.animateWithDuration(0.4) () -> Void in


            self.bottomConstraint.constant = self.keyboard.height + 4

            self.tableDiff = self.tableView.frame.size.height
        
    

    //func loading when keyboard is hidden
    func keyboardWillHide(notification : NSNotification)

        //move UI down
        UIView.animateWithDuration(0.4)() -> Void in


        

    

    //alignment function
    func alignment()


        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 160.0

        //set CommentTextView Style
        commentTextView.layer.cornerRadius = commentTextView.frame.size.width / 50


        //delegates
        commentTextView.delegate = self
        tableView.delegate = self
        tableView.dataSource = self

        //assign reseting values
        tableViewHeight = tableView.frame.size.height
        commentHeight = commentTextView.frame.size.height
        commentY = commentTextView.frame.origin.y


    



    //while writing something
    func textViewDidChange(textView: UITextView) 

        //disable button if entered no text
        let spacing = NSCharacterSet.whitespaceAndNewlineCharacterSet()

        //It shown when user entered type
        if !commentTextView.text.stringByTrimmingCharactersInSet(spacing).isEmpty
            sendButton.enabled = true
        else 

            sendButton.enabled = false
        


        // + paragraph

        if textView.contentSize.height > textView.frame.size.height && textView.frame.height < 130

            //find difference to add
            let difference = textView.contentSize.height - textView.frame.size.height
            self.tableDiff = difference

            //redefine frame of commentText
            textView.frame.origin.y = textView.frame.origin.y - difference
            textView.frame.size.height = textView.contentSize.height

            //move up tableView
            if textView.contentSize.height + keyboard.height + commentY >= tableView.frame.size.height 
                tableView.frame.size.height = tableView.frame.size.height - difference


            

        

        // - parapraph

        else if textView.contentSize.height < textView.frame.size.height 

            //find difference to deduct
            let difference = textView.frame.size.height - textView.contentSize.height
            self.tableDiff = difference
            //redefine frame of commentText
            textView.frame.origin.y = textView.frame.origin.y + difference
            textView.frame.size.height = textView.contentSize.height

            //move down tableview
            if textView.contentSize.height + keyboard.height + commentY > tableView.frame.size.height 

                tableView.frame.size.height = tableView.frame.size.height + difference
            

        


    

//点击发送按钮 @IBAction func sendButtonTapped(sender: AnyObject)

    print("send tapped")
    //STEP1. Add row in tableView
    usernameArray.append(PFUser.currentUser()!.username!)
    profileArray.append(PFUser.currentUser()?.objectForKey("profileImg") as! PFFile)
    dateArray.append(NSDate())
    commentArray.append(commentTextView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()))
    tableView.reloadData()

    //STEP2. Send comment to server
    let commentObj = PFObject(className: "comments")
    commentObj["to"] = commentUUID.last
    commentObj["username"] = PFUser.currentUser()?.username
    commentObj["profileImg"] = PFUser.currentUser()?.valueForKey("profileImg")
    commentObj["comment"] = commentTextView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    commentObj.saveEventually()

    //Scroll to bottom
    self.tableView.scrollToRowAtIndexPath(NSIndexPath(forItem: commentArray.count - 1, inSection: 0), atScrollPosition: UITableViewScrollPosition.Bottom, animated: false)

    //STEP 3. Reset UI
    sendButton.enabled = false
    commentTextView.text = ""
    commentTextView.frame.size.height = commentHeight
    commentTextView.frame.origin.y = sendButton.frame.origin.y


    //TableView Reset....Is Not working.
    tableView.frame.size.height = tableView.frame.size.height


【问题讨论】:

【参考方案1】:

看起来您正在使用自动布局,因此您应该更新约束,而不是更新 tableView.frame。为您的tableView heightConstraint 创建一个IBOutlet,然后将更新后的高度设置为它。

IBOutlet weak var tableHeightConstraint: NSLayoutConstraint!

//calculate the height and update the constant
tableHeightConstraint.constant = updatedTableHeight

同样从您的代码来看,您似乎只是在自行更新tableView.frame.height。您应该计算该值并设置为上述约束。

【讨论】:

你能帮我吗?我添加了表格高度的 IBOutlet。如何更改 textViewDidChange 的功能。 当我使用自动布局时... textView.frame 应该改为收缩吗? //重定义commentText的frame textView.frame.origin.y = textView.frame.origin.y - 区别textView.frame.size.height = textView.contentSize.height And.. // + 段落,// - 段落... 如何设置 tableHeightConstraint.constant?我试过ableViewConstraintH.constant = tableView.frame.size.height - 差异。它只是将 frame.size.height 更改为约束。但它似乎不起作用。抱歉问太多了..为你

以上是关于编辑文本后如何重置tableview的高度的主要内容,如果未能解决你的问题,请参考以下文章

如何从 tableview 的单元格中删除 imageView,并重置单元格的高度

如何动态调整tableheaderview的高度

如何在tableview Cell内设置tableView的自动高度?

输入长文本时如何调整文本视图的大小?

tableView.tableHeaderView赋值后立即刷新

swift中tableView的单元格高度扩展时更改标签文本