Home > OS >  Swift: Add border to one side of a table View cell
Swift: Add border to one side of a table View cell

Time:03-15

How Can I add a gray border color to the right side of my custom cells in table view? I have a custom cells of my table and want to add border color to all of it but in on the right side only to indicate that it is possible to swipe right, Here is my custom cell class:

import UIKit

class AdminCustomCell: UITableViewCell {


@IBOutlet weak var MainView: UIView!
@IBOutlet weak var BackView: UIView!

@IBOutlet weak var Km: UILabel!
override func awakeFromNib() {
    super.awakeFromNib()

    self.BackView.layer.borderWidth = 1
    self.BackView.layer.cornerRadius = 20
    self.BackView.layer.borderColor = UIColor.white.cgColor
    self.BackView.layer.masksToBounds = true

    self.MainView.layer.shadowOpacity = 0.18
    self.MainView.layer.shadowOffset = CGSize(width: 0, height: 2)
    self.MainView.layer.shadowRadius = 6
    self.MainView.layer.shadowColor = UIColor.black.cgColor
    self.MainView.layer.masksToBounds = false
}

//@IBOutlet weak var ParkingView: UIView!
@IBOutlet weak var Label: UILabel!
@IBOutlet weak var Alert: UILabel!
@IBOutlet weak var Logos: UIImageView!
@IBOutlet weak var ParkingView: UIView!

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}


override func layoutSubviews() {
    super.layoutSubviews()

    ParkingView.frame = ParkingView.frame.inset(by: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
}

}

CodePudding user response:

You could try using CALayer or override drawRect and draw a line where you want.

Here is an example using CALayer

private func addRightBorder() {
    let border = CALayer()
    
    let borderWidth: CGFloat = 5
    
    // Set the color your want
    border.backgroundColor = UIColor.red.cgColor
    
    // Create a rect only on the right of the view
    border.frame = CGRect(x: bounds.maxX - borderWidth,
                          y: 0,
                          width: borderWidth,
                          height: bounds.maxY)
    
    layer.addSublayer(border)
}
  • Related