16
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Swift】枠線を任意の場所につける

Posted at

小ネタです。
上下左右の任意の位置に枠線を配置したくて、それがtextFieldのみでなく、LabelやViewにまでかかってくる始末だったので、こちらの記事を参考に任意の位置に枠線をつける拡張クラスを作ってみました。
https://qiita.com/Simmon/items/5f8aae6b23e3c82cb735

CustomView
enum BorderPosition {
    case top
    case left
    case right
    case bottom
}

extension UIView {
    /// 特定の場所にborderをつける
    ///
    /// - Parameters:
    ///   - width: 線の幅
    ///   - color: 線の色
    ///   - position: 上下左右どこにborderをつけるか
    func addBorder(width: CGFloat, color: UIColor, position: BorderPosition) {
        
        let border = CALayer()
        
        switch position {
        case .top:
            border.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: width)
            border.backgroundColor = color.cgColor
            self.layer.addSublayer(border)
        case .left:
            border.frame = CGRect(x: 0, y: 0, width: width, height: self.frame.height)
            border.backgroundColor = color.cgColor
            self.layer.addSublayer(border)
        case .right:
            print(self.frame.width)
            
            border.frame = CGRect(x: self.frame.width - width, y: 0, width: width, height: self.frame.height)
            border.backgroundColor = color.cgColor
            self.layer.addSublayer(border)
        case .bottom:
            border.frame = CGRect(x: 0, y: self.frame.height - width, width: self.frame.width, height: width)
            border.backgroundColor = color.cgColor
            self.layer.addSublayer(border)
        }
    }
}
ViewController
class ViewController: UIViewController {
    @IBOutlet weak var textView: UITextView!

    override func viewDidLayoutSubviews() {
        self.textView.addBorder(width: 0.5, color: UIColor.black, position: .right)
        self.textView.addBorder(width: 0.5, color: UIColor.black, position: .bottom)
        self.textView.addBorder(width: 0.5, color: UIColor.black, position: .top)
        self.textView.addBorder(width: 0.5, color: UIColor.black, position: .left)
    }
}

上記のやり方だとUIViewを拡張しているので様々なクラスで使うことができますが、枠線をviewの内側に生成しているので線の幅が広いとLabel等の文字に被ったりします。
また、部品のサイズが動的に変わったりするとタイミング次第で表示される位置がズレます。

他のいい方法があれば改善&ご教授お願いいたします。

16
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?