เพิ่ม Border ให้ Image View ง่ายๆ
ขั้นตอนที่ 1: สร้างโปรเจกต์
Xcode → New Project → Single View Application → ชื่อ "BorderToImage"
สร้าง Image View + ปุ่ม กดปุ่มจะเพิ่ม Border
ขั้นตอนที่ 2: ออกแบบ UI
Main.storyboard: Image View + ปุ่ม

ขั้นตอนที่ 3: สร้าง Outlet/Action
@IBOutlet imgView @IBAction btnAddBorder
ขั้นตอนที่ 4: โค้ดเพิ่ม Border
@IBAction func btnAddBorder(_ sender: Any) {
imgView.layer.borderColor = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0).cgColor
imgView.layer.masksToBounds = true
imgView.contentMode = .scaleToFill
imgView.layer.borderWidth = 5
}โค้ดเต็มและผลลัพธ์
import UIKit
class ViewController: UIViewController {
@IBOutlet var imgView: UIImageView!
override func viewDidLoad() { super.viewDidLoad() }
@IBAction func btnAddBorder(_ sender: Any) {
imgView.layer.borderColor = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0).cgColor
imgView.layer.masksToBounds = true
imgView.contentMode = .scaleToFill
imgView.layer.borderWidth = 5
}
}
