Hiren Prajapati Hiren Prajapati - 1 month ago 9
Swift Question

how to use ViewWithTag in Swift?

I'm new to Swift, however I work in Objective-C before. I'm having issue in checkin if the cell is being reused in UITableView or not.

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()

I have used MGSwipebleCell. While scrolling lblMessage overlaps. Even we can not check if cell is nil or not. So how to use viewWithTag in this situation? Thnaks

Rob Rob

Rather than using viewWithTag, you can register a custom class with the cell reuse identifier. Then you can access the label using a property of that subclass:

override func 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()

            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")