Ios UITableViewCell在首次加载时变窄

Ios UITableViewCell在首次加载时变窄,ios,swift,uitableview,ios8,Ios,Swift,Uitableview,Ios8,当单元格第一次出现时,它们看起来就像我的图片所示。如果向上滚动,然后向下滚动,让它们再次显示,它们将是正常的。顶部的三个单元格始终是正常的,而底部是缩小的。这是我的代码` import UIKit class AllCommentsViewController: UIViewController { @IBAction func unwindToAllComments(sender: UIStoryboardSegue){ if sender.identifier == "unwin

当单元格第一次出现时,它们看起来就像我的图片所示。如果向上滚动,然后向下滚动,让它们再次显示,它们将是正常的。顶部的三个单元格始终是正常的,而底部是缩小的。这是我的代码`

import UIKit

class AllCommentsViewController: UIViewController {

@IBAction func unwindToAllComments(sender: UIStoryboardSegue){
    if sender.identifier == "unwindToAllComments"{
    }
}

override func awakeFromNib() {
    let photo = ZLLPhoto(withoutDataWithObjectId: "55cd717700b0875fb6cc125f")
    photo.fetch()
    self.photo = photo
}

var photo: ZLLPhoto!

var comments = [ZLLComment]()

@IBAction func commentButtonClicked(sender: UIButton){
    performSegueWithIdentifier("comment", sender: nil)
}

private func initialCommentsQuery() -> AVQuery {
    let query = ZLLComment.query()
    query.whereKey("photo", equalTo: photo)
    query.limit = 20
    query.orderByDescending("likeCount")
    query.addDescendingOrder("createdAt")
    query.includeKey("score")
    query.includeKey("author")
    return query
}

func getFirst(){
    initialCommentsQuery().findObjectsInBackgroundWithBlock { (objects, error) -> Void in
        if error == nil {
            if objects.count != 0 {
                let comments = objects as! [ZLLComment]
                self.comments = comments

                var indexPaths = [NSIndexPath]()
                for i in 0..<objects.count{
                    var indexPath = NSIndexPath(forRow: i, inSection: 2)
                    indexPaths.append(indexPath)
                }

                self.tableView.beginUpdates()
                self.tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .None)
                self.tableView.endUpdates()
                self.tableView.footer.endRefreshing()
                self.tableView.footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "loadMore")
                self.tableView.header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "refresh")
            }
        }else{
            print(error)
        }
        self.tableView.footer.endRefreshing()
    }
  }

func loadMore(){
    let last = comments.last!
    let query = initialCommentsQuery()

    query.whereKey("likeCount", lessThanOrEqualTo: last.likeCount)
    query.whereKey("createdAt", lessThan: last.createdAt)

    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
        if error == nil {
            if objects.count != 0{
                var indexPaths = [NSIndexPath]()
                for i in 0..<objects.count{
                    let indexPath = NSIndexPath(forRow: self.comments.count + i, inSection: 2)
                    indexPaths.append(indexPath)
                }

                let comments = objects as! [ZLLComment]
                self.comments.extend(comments)

                self.tableView.beginUpdates()
                self.tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .None)
                self.tableView.endUpdates()
            }
        }else{
            print(error)
        }
        self.tableView.footer.endRefreshing()
    }
}

func refresh(){
    let first = comments.first!
    let query = initialCommentsQuery()
    query.whereKey("likeCount", greaterThanOrEqualTo: first.likeCount)
    query.whereKey("createdAt", greaterThan: first.createdAt)

    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
        if error == nil {
            if objects.count != 0 {
                var comments = objects as! [ZLLComment]
                comments.extend(self.comments)
                self.comments = comments

                var indexPaths = [NSIndexPath]()
                for i in 0..<objects.count{
                    var indexPath = NSIndexPath(forRow: i, inSection: 2)
                    indexPaths.append(indexPath)
                }

                self.tableView.beginUpdates()
                self.tableView.insertRowsAtIndexPaths(indexPaths,
                    withRowAnimation: UITableViewRowAnimation.None)
                self.tableView.endUpdates()

            }
        }else{
            print(error)
        }
        self.tableView.header.endRefreshing()
    }
}

@IBOutlet weak var commentButton: UIButton!

@IBOutlet weak var photoTitle: UILabel!{
    didSet{
        photoTitle.text = photo.title
    }
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "comment" {
        let VC = segue.destinationViewController as! CommentPhotoViewController
        VC.photo = photo
    }else if segue.identifier == "showUser"{
        let VC = segue.destinationViewController as! UserInfoTableViewController
        VC.user = sender as! ZLLUser
    }
}


@IBAction func likeButtonClicked(sender: UIButton) {
    let indexPath = tableView.indexPathForCellContainingView(sender)!
    let comment = comments[indexPath.row]
    let I = ZLLUser.currentUser()
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! CommentCell

    if !cell.liked{
        I.likeComment(comment, completion: { (error) -> Void in
            if error == nil {
                comment.incrementKey("likeCount")
                cell.likeCount += 1
                cell.liked = true
            }else{
                print(error)
            }
        })
    }else{
        I.unlikeComment(comment, completion: { (error) -> Void in
            if error == nil{
                comment.incrementKey("likeCount", byAmount: -1)
                cell.likeCount -= 1
                cell.liked = false
            }else{
                print(error)
            }
        })
    }
}
//XIBload
@IBOutlet weak var tableView: UITableView!

@IBOutlet var titleScoreLabel: UILabel?

@IBOutlet var titleLabel: UILabel?

@IBOutlet var photoCell: UITableViewCell!

override func viewDidLoad() {

    NSBundle.mainBundle().loadNibNamed("PhotoCell", owner: self, options: nil)

    tableView.footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "getFirst")

    let query = ZLLScore.query()
    query.whereKey("photo", equalTo: photo)
    query.whereKey("scorer", equalTo: ZLLUser.currentUser())
    query.countObjectsInBackgroundWithBlock { (count, error) -> Void in
        if error == nil {
            if count > 0{
                self.commentButton.setImage(UIImage(named: "comments_add_comment")!, forState: UIControlState.Normal)
            }
        }else{
            print(error)
        }
    }
}

}

extension AllCommentsViewController: UITableViewDataSource, UITableViewDelegate {

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 44
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 3
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    switch indexPath.section {
    case 0:
        let cell = tableView.dequeueReusableCellWithIdentifier("photoCell") as! PhotoCell
        cell.loadPhoto2(photo)
        return cell
    case 1:
        tableView
        let cell = tableView.dequeueReusableCellWithIdentifier("commentCell", forIndexPath: indexPath) as! CommentCell
        cell.loadPhotoInfo(photo)
        return cell
    default:
        let cell = tableView.dequeueReusableCellWithIdentifier("commentCell", forIndexPath: indexPath) as! CommentCell
        if indexPath.row == 0{
            cell.smallTagImage.image = UIImage(named: "jian")
            return cell
        }
        cell.delegate = self
        cell.loadComment(comments[indexPath.row])
        return cell
    }
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch section{
    case 2:
        return comments.count
    default:
        return 1
    }
}

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 1 
}

func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    switch section{
    case 0:
        return 1
    default:
        return 10
    }
}
}

extension AllCommentsViewController: PhotoCellDelegate{
func photoCellDidTapUserField(photoCell: PhotoCell) {
}

func photoCellDidClickShareButton(photoCell: PhotoCell) {
    //
    let indexPath = tableView.indexPathForCell(photoCell)!

    let share = UIAlertController(title: "分享图片", message: "\(photo.title)", preferredStyle: UIAlertControllerStyle.ActionSheet)
    let weibo = UIAlertAction(title: "微博", style: UIAlertActionStyle.Default) { (action) -> Void in

        if !WeiboSDK.isWeiboAppInstalled(){
            ZLLViewModel.showHintWithTitle("未安装微博应用", on: self.view)
            return
        }

        if !ShareSDK.hasAuthorizedWithType(ShareTypeSinaWeibo){
            let authorize = UIAlertController(title: "未获取授权", message: "是否要获取授权", preferredStyle: UIAlertControllerStyle.Alert)
            let confirm = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
                ShareSDK.getUserInfoWithType(ShareTypeSinaWeibo, authOptions: nil, result: { (result, userInfo, errorInfo) -> Void in
                    if !result {
                        ZLLViewModel.showHintWithTitle("授权失败!", on: self.view)
                        return
                    }

                    let image = ShareSDK.imageWithData(self.photo.imageFile.getData(), fileName: "test1", mimeType: "")
                    let content = ShareSDK.content("a", defaultContent: "b", image: image, title: "c", url: "", description: "d", mediaType: SSPublishContentMediaTypeImage)
                    ShareSDK.clientShareContent(content, type: ShareTypeSinaWeibo, statusBarTips: true, result: { (type, state, shareInfo, errorInfo, end) -> Void in

                    })
                })
            })
            let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
            authorize.addAction(confirm)
            authorize.addAction(cancel)

            self.presentViewController(authorize, animated: true, completion: nil)
            return
        }

        let image = ShareSDK.imageWithData(self.photo.imageFile.getData(), fileName: "test1", mimeType: "")
        let content = ShareSDK.content("a", defaultContent: "b", image: image, title: "c", url: "", description: "d", mediaType: SSPublishContentMediaTypeImage)
        ShareSDK.clientShareContent(content, type: ShareTypeSinaWeibo, statusBarTips: true, result: { (type, state, shareInfo, errorInfo, end) -> Void in

        })
    }

    let qZone = UIAlertAction(title: "qq空间", style: UIAlertActionStyle.Default) { (action) -> Void in
        //

        if !QQApiInterface.isQQInstalled(){
            ZLLViewModel.showHintWithTitle("未安装腾讯QQ", on: self.view)
            return
        }

        if !ShareSDK.hasAuthorizedWithType(ShareTypeQQSpace){
            let authorize = UIAlertController(title: "未获取授权", message: "是否要获取授权", preferredStyle: UIAlertControllerStyle.Alert)
            let confirm = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
                ShareSDK.getUserInfoWithType(ShareTypeQQSpace, authOptions: nil, result: { (result, userInfo, errorInfo) -> Void in
                    if !result {
                        ZLLViewModel.showHintWithTitle("授权失败!", on: self.view)
                        return
                    }

                    let image = ShareSDK.imageWithData(self.photo.imageFile.getData(), fileName: "test1", mimeType: "")
                    let content = ShareSDK.content("a", defaultContent: "b", image: image, title: "c", url: "", description: "d", mediaType: SSPublishContentMediaTypeImage)
                    ShareSDK.clientShareContent(content, type: ShareTypeQQSpace, statusBarTips: true, result: { (type, state, shareInfo, errorInfo, end) -> Void in

                    })
                })
            })
            let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
            authorize.addAction(confirm)
            authorize.addAction(cancel)

            self.presentViewController(authorize, animated: true, completion: nil)
            return
        }
        let image = UIImage(data: self.photo.imageFile.getData())
        let data = UIImageJPEGRepresentation(image, 0.1)

        let attachment = ShareSDK.imageWithData(data, fileName: "test1", mimeType: "")
        let content = ShareSDK.content("a", defaultContent: "b", image: attachment, title: "c", url: "www.baidu.com", description: "d", mediaType: SSPublishContentMediaTypeImage)
        ShareSDK.clientShareContent(content, type: ShareTypeQQSpace, statusBarTips: true, result: { (type, state, shareInfo, errorInfo, end) -> Void in

        })
    }

    let weixin = UIAlertAction(title: "微信好友", style: UIAlertActionStyle.Default) { (action) -> Void in
        if !QQApiInterface.isQQInstalled(){
            ZLLViewModel.showHintWithTitle("未安装腾讯QQ", on: self.view)
            return
        }

        if !ShareSDK.hasAuthorizedWithType(ShareTypeQQSpace){
            let authorize = UIAlertController(title: "未获取授权", message: "是否要获取授权", preferredStyle: UIAlertControllerStyle.Alert)
            let confirm = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
                ShareSDK.getUserInfoWithType(ShareTypeQQ, authOptions: nil, result: { (result, userInfo, errorInfo) -> Void in
                    if !result {
                        ZLLViewModel.showHintWithTitle("授权失败!", on: self.view)
                        return
                    }

                    let image = ShareSDK.imageWithData(self.photo.imageFile.getData(), fileName: "test1", mimeType: "")
                    let content = ShareSDK.content("a", defaultContent: "b", image: image, title: "c", url: "", description: "d", mediaType: SSPublishContentMediaTypeImage)
                    ShareSDK.clientShareContent(content, type: ShareTypeQQ, statusBarTips: true, result: { (type, state, shareInfo, errorInfo, end) -> Void in

                    })
                })
            })
            let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
            authorize.addAction(confirm)
            authorize.addAction(cancel)

            self.presentViewController(authorize, animated: true, completion: nil)
            return
        }
        let image = ShareSDK.imageWithData(self.photo.imageFile.getData(), fileName: "test1", mimeType: "")
        let content = ShareSDK.content("a", defaultContent: "b", image: image, title: "c", url: "", description: "d", mediaType: SSPublishContentMediaTypeImage)

        ShareSDK.clientShareContent(content, type: ShareTypeQQ, statusBarTips: true, result: { (type, state, shareInfo, errorInfo, end) -> Void in

        })
    }


    let pengyouquan = UIAlertAction(title: "朋友圈", style: UIAlertActionStyle.Default) { (action) -> Void in

    }

    let cancl = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
    share.addAction(weibo)
    share.addAction(qZone)
    share.addAction(weixin)
    share.addAction(pengyouquan)
    share.addAction(cancl)
    self.presentViewController(share, animated: true, completion: nil)
}

func photoCellDidClickMoreButton(photoCell: PhotoCell) {

    let indexPath = tableView.indexPathForCell(photoCell)!

    let alertController = UIAlertController(title: "更多", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)

    let report = UIAlertAction(title: "举报", style: UIAlertActionStyle.Default) { (alertAction) -> Void in
        let confirmReport = UIAlertController(title: "确认举报?", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
        let delete = UIAlertAction(title: "确认", style: UIAlertActionStyle.Destructive) { (alertAction) -> Void in
            let report = ZLLReport.new()
            report.reportedPhoto = self.photo
            report.reporter = ZLLUser.currentUser()
            let success = report.save()
            if success{
                ZLLViewModel.showHintWithTitle("举报成功", on: self.view)
            }else{
                ZLLViewModel.showHintWithTitle("举报失败", on: self.view)
            }
        }
        let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
        confirmReport.addAction(delete)
        confirmReport.addAction(cancel)
        self.presentViewController(confirmReport, animated: true, completion: nil)
    }
    alertController.addAction(report)

    if photo.owner.objectId == ZLLUser.currentUser().objectId{
        let delete = UIAlertAction(title: "删除图片", style: UIAlertActionStyle.Destructive) { (alertAction) -> Void in
            let confirmDelete = UIAlertController(title: "确认删除?", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
            let delete = UIAlertAction(title: "确认", style: UIAlertActionStyle.Destructive) { (alertAction) -> Void in
                let success = self.photo.delete()
                self.photo.deleteInBackgroundWithBlock({ (success, error) -> Void in
                    if success{
                        self.performSegueWithIdentifier("deleteComplete", sender: nil)
                        ZLLViewModel.showHintWithTitle("删除成功", on: self.view)
                        self.myPopBackButtonClicked(nil)
                    }else{
                        print(error)
                    }
                })
            }
            let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
            confirmDelete.addAction(delete)
            confirmDelete.addAction(cancel)
            self.presentViewController(confirmDelete, animated: true, completion: nil)
        }
        alertController.addAction(delete)
    }

    let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
    alertController.addAction(cancelAction)
    self.presentViewController(alertController, animated: true, completion: nil)
}
}

extension AllCommentsViewController: CommentCellProtocol{
func commentCellDidTapAuthorLabel(cell: CommentCell) {
    let indexPath = tableView.indexPathForCell(cell)!
    let comment = comments[indexPath.row]
    let user = comment.author
    performSegueWithIdentifier("showUser", sender: user)
}
}`
导入UIKit
类AllCommentsViewController:UIViewController{
@iAction func unwindToAllComments(发件人:UIStoryboardSegue){
如果sender.identifier==“unwindToAllComments”{
}
}
重写func awakeFromNib(){
let photo=ZLLPhoto(无数据且对象ID为“55cd717700b0875fb6cc125f”)
photo.fetch()
self.photo=照片
}
照片:ZLLPhoto!
var注释=[ZLLComment]()
@iAction func commentButtonClicked(发件人:UIButton){
performsguewithidentifier(“注释”,发件人:nil)
}
private func initialCommentsQuery()->AVQuery{
let query=ZLLComment.query()
query.whereKey(“照片”,equalTo:photo)
query.limit=20
query.orderByDescending(“likeCount”)
query.addDensingOrder(“createdAt”)
查询。包含关键字(“分数”)
query.includeKey(“作者”)
返回查询
}
func getFirst(){
InitialCommentSquary().FindObjectsInBackgroundithBlock{(对象,错误)->中的Void
如果错误==nil{
如果objects.count!=0{
让注释=对象为![ZLLComment]
self.comments=注释
var indexpath=[NSIndexPath]()
因为我在0中…在0中无效
如果错误==nil{
如果objects.count!=0{
var indexpath=[NSIndexPath]()
因为我在0中…在0中无效
如果错误==nil{
如果objects.count!=0{
var comments=对象为![ZLLComment]
comments.extend(self.comments)
self.comments=注释
var indexpath=[NSIndexPath]()
因为我在0中…在0中无效
如果错误==nil{
comment.incrementKey(“likeCount”)
cell.likeCount+=1
cell.com=true
}否则{
打印(错误)
}
})
}否则{
I.unlikeComment(注释,完成:{(错误)->Void in
如果错误==nil{
comment.incrementKey(“likeCount”,按金额:-1)
cell.likeCount-=1
cell.com=false
}否则{
打印(错误)
}
})
}
}
//锡伯负荷
@IBVAR表格视图:UITableView!
@IBOutlet var titleScoreLabel:UILabel?
@IBVAR标题标签:UILabel?
@IBVAR光电管:UITableViewCell!
重写func viewDidLoad(){
NSBundle.mainBundle().loadNibNamed(“光电管”,所有者:self,选项:nil)
tableView.footer=MJRefreshAutoNormalFooter(refreshingTarget:self,refreshingAction:“getFirst”)
let query=ZLLScore.query()
query.whereKey(“照片”,equalTo:photo)
query.whereKey(“scorer”,equalTo:ZLLUser.currentUser())
query.countObjectsInBackgroundWithBlock{(计数,错误)->中的Void
如果错误==nil{
如果计数>0{
self.commentButton.setImage(UIImage(名为:“comments\u add\u comment”)!,用于状态:UIControlState.Normal)
}
}否则{
打印(错误)
}
}
}
}
扩展AllCommentsViewController:UITableViewDataSource,UITableViewDelegate{
func tableView(tableView:UITableView,estimatedheightforrowatinedexpath indexath:NSIndexPath)->CGFloat{
返回44
}
func tableView(tableView:UITableView,heightForRowAtIndexPath:nsindepath)->CGFloat{
返回UITableViewAutomaticDimension
}
func numberOfSectionsInTableView(tableView:UITableView)->Int{
返回3
}
func tableView(tableView:UITableView,cellForRowAtIndexPath:nsindepath)->UITableView单元格{
开关indexPath.section{
案例0:
让cell=tableView.dequeueReusableCellWithIdentifier(“photoCell”)作为!photoCell
单元格。加载照片2(照片)
返回单元
案例1:
桌面视图
让cell=tableView.dequeueReusableCellWithIdentifier(“commentCell”,forIndexPath:indexPath)作为!commentCell
cell.loadPhotoInfo(照片)
返回单元
违约:
让cell=tableView.dequeueReusableCellWithIdentifier(“commentCell”,forIndexPath:indexPath)作为!commentCell
如果indexath.row==0{
cell.smallTagImage.image=UIImage(名为:“健”)
返回单元
}
cell.delegate=self
cell.loadComment(注释[indexPath.row])
返回单元
}
}
func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int{
开关段{
案例2:
return comments.count
违约:
返回1
}
}
func tableView(tableView:UITableView,heightForHeaderInSection:Int)->CGFloat{
返回1
}
func tableView(tableView:UITableView,heightforfooterInstruction节:Int)->CGFloat{
开关段{
案例0:
返回1
违约:
返回10
}
}
}
扩展名AllCommentsViewController:光电元件委派{
func光电元件DIDTAPUserField(光电元件:光电元件){
}
func光电管单击共享按钮(光电管:光电管){
//
让indexPath=tableView.indexPathForCell(光电池)!
let share=UIAlertController(标题:分享图片", 消息:“\(photo.title)”,首选样式:UIAlertControllerStyle.ActionSheet)
让微博=UIAlertAction(标题:微博,样式:UIAlertActionStyle.Default){(操作)->Void in
if!WeiboSDK.isWeiboAppInstalled(){
ZLLViewModel.showHintWithTitle(“未安装微博应用,on:self.view)
返回
}
if!ShareSDK.hasAuthorizedWithType(ShareTypeSinaWeibo){
let authorize=UIAlertController(标题:未获取授权,消息:是否要获取授权,首选样式:UIAlertControllerStyle.Alert)
let confirm=UIAlertAction(标题:确认,样式:UIAlertActionStyle.Default,处理程序:{(操作)
override func didMoveToSuperview() {
    layoutIfNeeded()
}