jjzjj

ios - 首次加载时 UITableViewCell 变窄

coder 2023-09-17 原文

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

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)
}
}`

最佳答案

在您的 PhotoCell 类中,添加这段代码。

override func didMoveToSuperview() {
    layoutIfNeeded()
}

关于ios - 首次加载时 UITableViewCell 变窄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32046228/

有关ios - 首次加载时 UITableViewCell 变窄的更多相关文章

  1. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  2. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  3. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  4. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  5. ruby-on-rails - 使用 config.threadsafe 时从 lib/加载模块/类的正确方法是什么!选项? - 2

    我一直致力于让我们的Rails2.3.8应用程序在JRuby下正确运行。一切正常,直到我启用config.threadsafe!以实现JRuby提供的并发性。这导致lib/中的模块和类不再自动加载。使用config.threadsafe!启用:$rubyscript/runner-eproduction'pSim::Sim200Provisioner'/Users/amchale/.rvm/gems/jruby-1.5.1@web-services/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in`co

  6. ruby-on-rails - 从应用程序中自定义文件夹内的命名空间自动加载 - 2

    我们目前正在为ROR3.2开发自定义cms引擎。在这个过程中,我们希望成为我们的rails应用程序中的一等公民的几个类类型起源,这意味着它们应该驻留在应用程序的app文件夹下,它是插件。目前我们有以下类型:数据源数据类型查看我在app文件夹下创建了多个目录来保存这些:应用/数据源应用/数据类型应用/View更多类型将随之而来,我有点担心应用程序文件夹被这么多目录污染。因此,我想将它们移动到一个子目录/模块中,该子目录/模块包含cms定义的所有类型。所有类都应位于MyCms命名空间内,目录布局应如下所示:应用程序/my_cms/data_source应用程序/my_cms/data_ty

  7. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  8. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  9. ruby-on-rails - 使用 gmaps4rails 动态加载谷歌地图标记 - 2

    如何只加载map边界内的标记gmaps4rails?当然,在平移和/或缩放后加载新的。与此直接相关的是,如何获取map的当前边界和缩放级别? 最佳答案 我是这样做的,我只在用户完成平移或缩放后替换标记,如果您需要不同的行为,请使用不同的事件监听器:在你看来(index.html.erb):{"zoom"=>15,"auto_adjust"=>false,"detect_location"=>true,"center_on_user"=>true}},false,true)%>在View的底部添加:functiongmaps4rail

  10. ruby-on-rails - 是否可以让 ActiveRecord 为使用 :joins option? 加载的行创建对象 - 2

    我需要做这样的事情classUser'User',:foreign_key=>'abuser_id'belongs_to:gameendclassGame['JOINabuse_reportsONusers.id=abuse_reports.abuser_id','JOINgamesONgames.id=abuse_reports.game_id'],:group=>'users.id',:select=>'users.*,count(distinctgames.id)ASgame_count,count(abuse_reports.id)asabuse_report_count',:

随机推荐