[英]How to add mask on UIImageView in Cell - Swift
I've a tableView and I'm trying to add black mask on each image in the cell not on the whole cell just on the image. 我有一个tableView,我试图在单元格中的每个图像上添加黑色蒙版,而不仅仅是在图像上的整个单元格上。 But I have two issues;
但是我有两个问题。
-It is masking the half cell from the left to the middle and each I scroll it is becoming darker. -它从左到中遮住了半个单元格,每滚动一次,它就会变得更暗。 So please where would be my issue?
所以,请问我的问题在哪里?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! PlacesTableViewCell
cell.backgroundImage.sd_setImageWithURL(NSURL(string: place.Image), placeholderImage: nil, options: .HighPriority)
}
class PlacesTableViewCell: UITableViewCell {
override func layoutSubviews() {
super.layoutSubviews()
maskArrangement()
}
func maskArrangement(){
var maskLayer = CALayer()
maskLayer.frame = CGRectMake(0, 0, backgroundImage.frame.size.width, backgroundImage.frame.size.height)
maskLayer.backgroundColor = UIColor(white: 0.0, alpha: 0.5).CGColor
//backgroundImage.layer.mask = maskLayer
backgroundImage.layer.addSublayer(maskLayer)
}
}
Every time cell is dequeued you are adding new sublayer to your backgroundImage. 每次单元出队时,您都会在backgroundImage中添加新的子层。 In this way it is getting darker when you scroll (when you dequeued your cells).
这样,当您滚动(将单元出队时),它会变得更暗。 I think you can add to your
PlacesTableViewCell
class at awakeFromNib
method if it has a .xib
file. 我想如果它具有
.xib
文件,则可以在awakeFromNib
方法PlacesTableViewCell
添加到PlacesTableViewCell
类中。
Meanwhile your image's frame should be half of the cell. 同时,图像的帧应为单元格的一半。 Use autolayout to fix it's frame (for instance, set width and height constraints) in your PLacesTableViewCell class.
使用自动布局可在PLacesTableViewCell类中修复其框架(例如,设置宽度和高度限制)。
In @Shripada 's way: 用@Shripada的方式:
class PlacesTableViewCell: UITableViewCell {
var maskLayer : CALayer
override func layoutSubviews() {
super.layoutSubviews()
maskArrangement()
}
func maskArrangement(){
if maskLayer == nil {
maskLayer.frame = CGRectMake(0, 0, backgroundImage.frame.size.width, backgroundImage.frame.size.height)
maskLayer.backgroundColor = UIColor(white: 0.0, alpha: 0.5).CGColor
//backgroundImage.layer.mask = maskLayer
backgroundImage.layer.addSublayer(maskLayer)
}
}
}
I haven't tried this code. 我没有尝试过这段代码。 But your solution can be like that.
但是您的解决方案可以是这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.