草庐IT

iOS collectionView.sizeForItemAtIndexPath 在 iPhone 6 之前中断

coder 2023-09-04 原文

我是 iOS 开发的新手,我正在尝试将我在 Android 上的项目移植到 iOS。我正在尝试在代码中构建一个 collectionView 作为实现的一部分。事情是因为 Collection View 中每个单元格中的数据可以是不同的字符串大小,每个单元格可以与其相邻单元格的大小不同。我正在试验附加的代码,但我注意到无论是物理设备还是模拟器中的 iPhone 6,用户界面看起来都符合预期……其他任何东西看起来都非常糟糕。似乎是 sizeForIndexItemAtPath 破坏了它。有什么想法吗?时间差

  import UIKit

  class ViewController: UIViewController,       UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    var collectionView: UICollectionView?
    var thisCellHeight: CGFloat = 0.0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let screenSize: CGRect = UIScreen.mainScreen().bounds
        let screenWidth = screenSize.width
        let screenHeight = screenSize.height

        var thisWidth = screenWidth - 10

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 70, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: thisWidth, height: 120)
        collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        //collectionView!.backgroundView?.backgroundColor = UIColor.blueColor()
        collectionView!.dataSource = self
        collectionView!.delegate = self
        collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        collectionView!.backgroundColor = hexStringToUIColor("#15ADFF")
        self.view.addSubview(collectionView!)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 14
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {



        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell
        cell.backgroundColor = UIColor.whiteColor()

        var typeLabel = UILabel(frame: CGRectMake(10, 0, 200, 21))
        typeLabel.text = "Card Type"
        typeLabel.font = typeLabel.font.fontWithSize(20)
        cell.addSubview(typeLabel)

        var titleLabel = UILabel(frame: CGRectMake(10, 25, 300, 21))

        titleLabel.text = "This Is The Article Title. This Is The Article Title. This Is The Article Title. This Is The Article Title."
        titleLabel.font = titleLabel.font.fontWithSize(20)
        titleLabel.numberOfLines = 0
        titleLabel.sizeToFit()
        self.thisCellHeight = CGFloat(titleLabel.frame.height)
        println("The title text is \(self.thisCellHeight) high")
        cell.addSubview(titleLabel)

        var authorLabel = UILabel(frame: CGRectMake(10, thisCellHeight + 30, 200, 21))
        authorLabel.text = "This Is The Article Author"
        authorLabel.font = authorLabel.font.fontWithSize(15)
        cell.addSubview(authorLabel)

        var timestampLabel = UILabel(frame: CGRectMake(10, thisCellHeight + 50, 200, 21))
        timestampLabel.text = "This Is The Timestamp"
        timestampLabel.font = timestampLabel.font.fontWithSize(15)
        cell.addSubview(timestampLabel)

        return cell
    }

    func hexStringToUIColor (hex:String) -> UIColor {
        var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString

        if (cString.hasPrefix("#")) {
            cString = cString.substringFromIndex(advance(cString.startIndex, 1))
        }

        if (countElements(cString) != 6) {
            return UIColor.grayColor()
        }

        var rgbValue:UInt32 = 0
        NSScanner(string: cString).scanHexInt(&rgbValue)

        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {


        return CGSizeMake(320, 350)


    }



}

最佳答案

您将布局上的项目大小设置为:

layout.itemSize = CGSize(width: thisWidth, height: 120)

而且你也在使用委托(delegate)方法

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSizeMake(320, 350)
}

第一个被第二个覆盖。 layout.itemSize 是每个项目的默认大小,前提是委托(delegate)方法 sizeForItemAtIndexPath 未被覆盖。您正在用看起来完全不同的东西覆盖 layout.itemSize。尝试删除委托(delegate)函数 sizeForItemAtIndexPath,这是否符合您的预期?

关于iOS collectionView.sizeForItemAtIndexPath 在 iPhone 6 之前中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28625990/

有关iOS collectionView.sizeForItemAtIndexPath 在 iPhone 6 之前中断的更多相关文章

  1. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  2. ruby - ruby 乘法语句中星号中断语法前的空格 - 2

    在添加一些空格以使代码更具可读性时(与上面的代码对齐),我遇到了这个:classCdefx42endendm=C.new现在这将给出“错误数量的参数”:m.x*m.x这将给出“语法错误,意外的tSTAR,期待$end”:2/m.x*m.x这里的解析器到底发生了什么?我使用Ruby1.9.2和2.1.5进行了测试。 最佳答案 *用于运算符(42*42)和参数解包(myfun*[42,42])。当你这样做时:m.x*m.x2/m.x*m.xRuby将此解释为参数解包,而不是*运算符(即乘法)。如果您不熟悉它,参数解包(有时也称为“spl

  3. ruby-on-rails - 如何处理 Grape 中特定操作的过滤器之前? - 2

    我正在我的Rails项目中安装Grape以构建RESTfulAPI。现在一些端点的操作需要身份验证,而另一些则不需要身份验证。例如,我有users端点,看起来像这样:moduleBackendmoduleV1classUsers现在如您所见,除了password/forget之外的所有操作都需要用户登录/验证。创建一个新的端点也没有意义,比如passwords并且只是删除password/forget从逻辑上讲,这个端点应该与用户资源。问题是Grapebefore过滤器没有像except,only这样的选项,我可以在其中说对某些操作应用过滤器。您通常如何干净利落地处理这种情况?

  4. ruby-on-rails - 在 Ruby on Rails 中发送响应之前如何等待多个异步操作完成? - 2

    在我做的一些网络开发中,我有多个操作开始,比如对外部API的GET请求,我希望它们同时开始,因为一个不依赖另一个的结果。我希望事情能够在后台运行。我找到了concurrent-rubylibrary这似乎运作良好。通过将其混合到您创建的类中,该类的方法具有在后台线程上运行的异步版本。这导致我编写如下代码,其中FirstAsyncWorker和SecondAsyncWorker是我编写的类,我在其中混合了Concurrent::Async模块,并编写了一个名为“work”的方法来发送HTTP请求:defindexop1_result=FirstAsyncWorker.new.async.

  5. ruby - 在 ASP 页面上 Mechanize 中断 - 2

    require'mechanize'agent=Mechanize.newlogin=agent.get('http://www.schoolnet.ch/DE/HomeDE.htm')agent.clicklogin.link_withtext:/Login/然后我得到Mechanize::UnsupportedSchemeError。 最佳答案 Mechanize不支持javascript但您可以将搜索字段添加到表单并为其分配搜索词并使用mechanize提交表单form=page.forms.firstform.add_fie

  6. ruby-on-rails - 在所有延迟的作业之前 Hook - 2

    是否可以在所有delayed_job任务之前运行一个方法?基本上,我们试图确保每个运行delayed_job的服务器都有我们代码的最新实例,所以我们想运行一个方法来在每个作业运行之前检查它。(我们已经有了“check”方法并在别处使用它。问题只是关于如何从delayed_job中调用它。) 最佳答案 现在有一种官方方法可以通过插件来做到这一点。这篇博文通过示例清楚地描述了如何执行此操作http://www.salsify.com/blog/delayed-jobs-callbacks-and-hooks-in-rails(本文中描述

  7. ruby - 可以正常中断的来自 Rake 的长时间运行的 shell 命令? - 2

    在几个项目中,我希望有一个类似rakeserver的rake任务,它将通过任何需要的方式开始为该应用程序提供服务。这是一个示例:task:serverdo%x{bundleexecrackup-p1234}end这行得通,但是当我准备停止它时,按Ctrl+c并没有正常关闭;它中断了Rake任务本身,它说rakeaborted!并给出堆栈跟踪。在某些情况下,我必须执行Ctrl+c两次。我可能可以用Signal.trap写一些东西来更优雅地中断它。有没有更简单的方法? 最佳答案 trap('SIGINT'){puts"Yourmessa

  8. ruby-on-rails - prawnto 显示新页面时不会中断的表格 - 2

    我有可变数量的表格和可变数量的行,我想让它们一个接一个地显示,但如果表格不适合当前页面,请将其放在下一页,然后继续。我已将表格放入事务中,以便我可以回滚然后打印它(如果高度适合当前页面),但我如何获得表格高度?我现在有这段代码pdf.transactiondopdf.table@data,:font_size=>12,:border_style=>:grid,:horizontal_padding=>10,:vertical_padding=>3,:border_width=>2,:position=>:left,:row_colors=>["FFFFFF","DDDDDD"]pdf.

  9. ruby-on-rails - define_method 在调用方法之前不使用变量? - 2

    我无法从for循环中获取变量。似乎i(var)是稍后计算的,而不是我完全需要的类定义。ree-1.8.7-2010.02>classPatree-1.8.7-2010.02?>foriin39..47ree-1.8.7-2010.02?>define_method("a#{i}".to_sym)doree-1.8.7-2010.02>putsiree-1.8.7-2010.02?>endree-1.8.7-2010.02?>endree-1.8.7-2010.02?>end#=>39..47ree-1.8.7-2010.02>p=Pat.new#=>#ree-1.8.7-2010.02

  10. ruby-on-rails - ActiveRecord:除非另有说明,否则在保存之前使所有文本字段都调用 strip - 2

    多年来,我在各种网站上遇到过各种问题,用户在字符串和文本字段的开头/结尾放置空格。有时这些会导致格式/布局问题,有时会导致搜索问题(即搜索顺序看起来不对,但实际上并非如此),有时它们实际上会使应用程序崩溃。我认为这会很有用,而不是像我过去所做的那样放入一堆before_save回调,向ActiveRecord添加一些功能以在保存之前自动调用任何字符串/文本字段上的.strip,除非我告诉它不是,例如do_not_strip:field_x,:field_y或类定义顶部的类似内容。在我去弄清楚如何做到这一点之前,有没有人看到更好的解决方案?明确一点,我已经知道我可以做到这一点:befor

随机推荐