每次 UITableView 的 CardView 尝试中内容可见时,阴影视图都会变暗

问题描述 投票:0回答:1

我正在尝试使用 Swift UIKit 中的 UITableView 实现卡片视图布局。当我使用下面的代码时,我得到了我想要的,但是每次单元格到达可见区域时,背景和阴影变得越来越暗。

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cell.contentView.backgroundColor = UIColor.clear
    let whiteRoundedView : UIView = UIView(frame: CGRectMake(15, 15, self.view.frame.size.width - 30, 90))
    whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 1.0])
    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 3.0
    whiteRoundedView.layer.shadowOffset = CGSizeMake(-1, 1)
    whiteRoundedView.layer.shadowOpacity = 0.5
    
    if !cell.contentView.subviews.contains(whiteRoundedView) {
        cell.contentView.addSubview(whiteRoundedView) //<- AAA
    }
    cell.contentView.sendSubviewToBack(whiteRoundedView)
}

AAA似乎每次都会打电话,无论检查如何,因为每次都通过了。

有人可以建议我实现这一目标的最佳方法吗???

enter image description here

swift uitableview uikit
1个回答
0
投票

正如@matt所说,cell是被重用的,这意味着

willDisplay cell
在cell的生命周期中会被多次调用,
whiteRoundedView
也会被多次添加。

你可以尝试这个方法。通过执行以下操作,您可以确保

whiteRoundedView
仅添加一次。

//If your cell was created from XIB/Storyboard
- (void)awakeFromNib {
    [super awakeFromNib];
    //Put the code for making shadow here
    let whiteRoundedView = UIView(frame: CGRectMake(15, 15, [[UIScreen mainScreen] bounds].size.width - 30, 90))
    ...
}

//If you manually create with code
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { 
    ...
    //Put the code for making shadow here
    let whiteRoundedView = UIView(frame: CGRectMake(15, 15, [[UIScreen mainScreen] bounds].size.width - 30, 90))
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.