奇怪的是,我似乎无法弄清楚为什么我无法在这段代码中返回 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()
的位置。
这是我认为可能会导致您遇到的情况的一种情况:
您在 xib 中创建一个自定义单元格(宽度可能为 320)
在初始化过程中,您调用了
addGradientForInformationBackground()
,当时单元格的宽度确实是 320 作为 xibcell 加载到 tableView 中,但 tableView 不接受与自身宽度不同的 cell,因此 tableView 以某种方式调用 cell.setFrame 来更改单元格的宽度
但是您添加的图层的框架不会改变
所以尝试调用prepareForReuse
中的添加图层方法检查图层是否存在,如果没有创建它
关于ios - 无法确定表格 View 单元格的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31017436/