我是Swift的新手,但之前我在Objective-C工作过。如果单元格在UITableView中被重用,我在签入时遇到问题。
let cell = tableView.dequeueReusableCellWithIdentifier(strCellId, forIndexPath:indexPath) as! MGSwipeTableCell
cell.backgroundColor = UIColor.clearColor()
let SMSObj = self.arraySMSContent[indexPath.row] as! SMSModel
let lblMessage = UILabel(frame: CGRectMake(15, 10, Constants.SCREEN_WIDTH/1.4, Constants.SCREEN_HEIGHT/11))
lblMessage.text = SMSObj.strSMSContent
lblMessage.textAlignment = NSTextAlignment.Left
lblMessage.numberOfLines = 2
lblMessage.textColor = UIColor.whiteColor()
cell.contentView.addSubview(lblMessage)
我使用过MGSwipebleCell。滚动lblMessage时重叠。即使我们无法检查细胞是否为零。那么如何在这种情况下使用viewWithTag呢? Thnaks
答案 0 :(得分:4)
您可以使用单元格重用标识符注册自定义类,而不是使用viewWithTag
。然后,您可以使用该子类的属性访问标签:
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(CustomCell.self, forCellReuseIdentifier: "CustomCell")
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
cell.smsLabel.text = ...
return cell
}
其中:
class CustomCell: MGSwipeTableCell {
var smsLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .Left
label.numberOfLines = 2
label.textColor = .whiteColor()
return label
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .blueColor()
contentView.addSubview(smsLabel)
NSLayoutConstraint.activateConstraints([
smsLabel.topAnchor.constraintEqualToAnchor(contentView.topAnchor, constant: 5),
smsLabel.bottomAnchor.constraintEqualToAnchor(contentView.bottomAnchor, constant: -5),
smsLabel.leadingAnchor.constraintEqualToAnchor(contentView.leadingAnchor, constant: 5),
smsLabel.trailingAnchor.constraintEqualToAnchor(contentView.trailingAnchor, constant: -5)
])
leftButtons = [MGSwipeButton(title: "Red", backgroundColor: .redColor())]
leftSwipeSettings.transition = .Rotate3D;
rightButtons = [MGSwipeButton(title: "Green", backgroundColor: .greenColor())]
rightSwipeSettings.transition = .Rotate3D;
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("not needed")
}
}
答案 1 :(得分:1)
有很多方法可以解决您的问题。请尝试:
if let lblMessage = cell.contentView.viewWithTag(9999) as? UILabel { //Tag
lblMessage.text = SMSObj.strSMSContent
}else{
let lblMessage = UILabel(frame: CGRectMake(15, 10, Constants.SCREEN_WIDTH/1.4, Constants.SCREEN_HEIGHT/11))
lblMessage.text = SMSObj.strSMSContent
lblMessage.textAlignment = NSTextAlignment.Left
lblMessage.numberOfLines = 2
lblMessage.textColor = UIColor.whiteColor()
lblMessage.tag = 9999 //Tag
cell.contentView.addSubview(lblMessage)
}