ios - 无法确定表格 View 单元格的宽度

标签 ios swift uitableview

奇怪的是,我似乎无法弄清楚为什么我无法在这段代码中返回 TableView 单元格的宽度。它位于我的自定义 UITableViewCell 中。我的目标是创建一个渐变,以扩展单元格的宽度,以便某些文本可以读取,并且不会被下面的图片遮挡。渐变出现,但似乎延伸到屏幕边缘约 9/10。我认为它可能与附件 View 有关,尽管我将其设置为“无”。经过几次调整后,我不明白为什么它没有扩展单元格的宽度。我不想对一个值进行硬编码以使其变得懒惰,只是想了解为什么会发生这种情况,以期在将来避免这种情况。谢谢!

//Adds Gradient to the information background to allow text to be readable
func addGradientForInformationBackground(){
    InformationBackground.backgroundColor = UIColor.clearColor();
    let gradient = CAGradientLayer();

    gradientFrame = self.frame;

    //build the colors array for the gradient
    var colors = NSArray(array:[UIColor.clearColor().CGColor,UIColor.blackColor().colorWithAlphaComponent(0.3).CGColor,UIColor.blackColor().colorWithAlphaComponent(0.5).CGColor,UIColor.blackColor().colorWithAlphaComponent(0.6).CGColor,UIColor.blackColor().colorWithAlphaComponent(0.7).CGColor,UIColor.blackColor().colorWithAlphaComponent(0.9).CGColor,UIColor.blackColor().CGColor]);

    //apply the colors and the gradient to the view
    gradient.colors = colors as [AnyObject];

    self.InformationBackground.layer.insertSublayer(gradient, atIndex: 0);
}

最佳答案

我认为这取决于您调用方法addGradientForInformationBackground()的位置。

这是我认为可能会导致您遇到的情况的一种情况:

  1. 您在 xib 中创建一个自定义单元格(宽度可能为 320)

  2. 在初始化过程中,您调用了addGradientForInformationBackground(),当时单元格的宽度确实是 320 作为 xib

  3. cell 加载到 tableView 中,但 tableView 不接受与自身宽度不同的 cell,因此 tableView 以某种方式调用 cell.setFrame 来更改单元格的宽度

  4. 但是您添加的图层的框架不会改变

所以尝试调用prepareForReuse中的添加图层方法检查图层是否存在,如果没有创建它

关于ios - 无法确定表格 View 单元格的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31017436/

相关文章:

ios - 有没有什么方法可以在不中断 UI 的情况下实现 avaudiosession .duckothers。 swift 2.0

ios - 像素大小的图标 - Swift 2.0

swift - Parse.com 错误 : can't add a non-pointer to a relation

带分页的 iOS TableView?

ios - 如何使 ios 应用程序使用 ios8 上的框架动态更新功能模块?

ios - 如何使用 Swift 淡入/淡出 tableviewcell 的背景色

ios - 接收 UDP 消息

ios - 如何在导航栏中 UISwitch 的状态更改时更改 UITableView cellrows?

ios - 如何在 UITableView 上 float 所有部分标题 View (或保持所有可见)?

iphone - 更改搜索栏中的键盘颜色和外观