เพิ่ม Border ด้านบนและล่างของ View ด้วย CALayer
ใช้ CALayer สร้างเส้นขอบบางๆ ที่ด้านบนและล่างของ UIView โดยไม่ต้องใช้รูปภาพ
ขั้นตอนที่ 1: สร้างโปรเจกต์
Xcode → Single View App → ชื่อ "AddBorderTopAndBottom"
ขั้นตอนที่ 2: เพิ่ม UIView ใน Storyboard
ลาก UIView มาวาง ตั้ง Constraints ให้อยู่กลางหน้าจอ
ขั้นตอนที่ 3: สร้าง IBOutlet
@IBOutlet weak var centerView: UIView!
ขั้นตอนที่ 4: สร้างฟังก์ชันเพิ่ม Border
func addTopAndBottomBorders() {
let thickness: CGFloat = 2.0
let color = UIColor.systemRed.cgColor
// Border ด้านบน
let topBorder = CALayer()
topBorder.frame = CGRect(x: 0, y: 0, width: centerView.frame.width, height: thickness)
topBorder.backgroundColor = color
// Border ด้านล่าง
let bottomBorder = CALayer()
bottomBorder.frame = CGRect(x: 0, y: centerView.frame.height - thickness, width: centerView.frame.width, height: thickness)
bottomBorder.backgroundColor = color
// เพิ่มเข้าไปใน layer ของ view
centerView.layer.addSublayer(topBorder)
centerView.layer.addSublayer(bottomBorder)
}
ขั้นตอนที่ 5: เรียกใน viewDidAppear
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
addTopAndBottomBorders()
}
ใช้ viewDidAppear เพื่อให้ frame ของ view คำนวณเสร็จแล้ว (Auto Layout layoutDone)
ขั้นตอนที่ 6: รันโปรเจกต์
จะเห็นเส้นสีแดงบางๆ ด้านบนและล่างของ View
ปรับปรุงสำหรับ Production
- เก็บ reference ของ layer ไว้ เพื่อลบ/อัปเดตภายหลังได้
- จัดการ Rotation/Size change: ใช้
viewDidLayoutSubviewsหรือoverride func layoutSubviews()ใน Custom View - พิจารณาใช้
CAShapeLayer+UIBezierPathสำหรับ Border แบบ Dash/Dotted
วิธีอื่น: ใช้ UIView แทน CALayer
let topLine = UIView()
topLine.backgroundColor = .systemRed
topLine.translatesAutoresizingMaskIntoConstraints = false
centerView.addSubview(topLine)
NSLayoutConstraint.activate([
topLine.topAnchor.constraint(equalTo: centerView.topAnchor),
topLine.leadingAnchor.constraint(equalTo: centerView.leadingAnchor),
topLine.trailingAnchor.constraint(equalTo: centerView.trailingAnchor),
topLine.heightAnchor.constraint(equalToConstant: 2)
])
วิธีนี้จัดการ Auto Layout ได้ดีกว่า และรองรับ Dynamic Size อัตโนมัติ