Daeng iOS

[iOS/UIKit] UIView 테두리 추가 (전체, 특정부분) 본문

IOS/UIKit

[iOS/UIKit] UIView 테두리 추가 (전체, 특정부분)

U_Daeng 2022. 10. 23. 20:02

1. 전체 테두리

btnView.layer.borderWidth = 0.5
btnView.layer.borderColor = UIColor.lightGray.cgColor

2. 부분 테두리

📍autoresizingMask 란?

- superview의 bounds가 변경될 때, receiver가 자체크기를 조정하는 방법을 결정하는 bit mask

(bit mask: 컴퓨터의 언어인 이진수를 사용하면 연산이 빠른 점을 이용해,
정수를 이진수로 표현하고 비트 연산을 통해 문제를 해결해 나가는 기법)

- view의 bounds 가 변경되면, 해당 view는 각 subview의 autoresizing mask에 따라 subview의 크기를 자동으로 조정한다.

- UIView에 설명된 상수를 결합하여 이 mask의 값을 지정한다.

즉, Autoresizing mask 를 사용하여, superview가 커지거나 줄어듦에 따라 subview의 크기나 위치를 조정한다!!

- flexible~Margin 을 지정해주지 않으면 그 방향으로 고정된다

(.flexibleTopMargin / .flexibleBottomMargin / .flexibleLeftMargin / .flexibleRightMargin)

따라서 아래의 부분 테두리를 그려주는 코드는 

AutoresizingMasks 슈퍼뷰와 함께 테두리 크기가 조정되도록 테두리를 CGRect로 그려준 방법인 것 같다!

아래 코드에서 upperView는 내가 추가한 UIView의 아울렛 변수,

0.5와 5부분에는 내가 설정하려는 테두리의 두께를 지정하면된다!!

 

💡위쪽만 테두리 

let border = UIView()
border.backgroundColor = .lightGray
border.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
border.frame = CGRect(x: 0, y: 0 , width: upperView.frame.width, height: 0.5)
upperView.addSubview(border)

 

💡아래쪽만 테두리

시작좌표의 y가 view의 높이에서 그리려는 테두리 두께 만큼 뺀 곳으로 지정한다.

let border = UIView()
border.backgroundColor = .lightGray
border.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
border.frame = CGRect(x: 0, y: upperView.frame.height - 0.5 , width: upperView.frame.width, height: 0.5)
upperView.addSubview(border)

 

💡오른쪽만 테두리
시작좌표의 x를 view의 너비에서 그리려는 테두리 두께 만큼 뺀 곳으로 지정한다.

let border = UIView()
border.backgroundColor = .red
border.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin]
border.frame = CGRect(x: upperView.frame.width - 5 , y: 0 , width: 5, height: upperView.frame.height)
upperView.addSubview(border)

 

💡왼쪽만 테두리

let border = UIView()
border.backgroundColor = .red
border.autoresizingMask = [.flexibleHeight, .flexibleRightMargin]
border.frame = CGRect(x:0 , y: 0 , width: 5, height: upperView.frame.height)
upperView.addSubview(border)

 

 


https://stackoverflow.com/questions/17355280/how-to-add-a-border-just-on-the-top-side-of-a-uiview/29033559#29033559

 

How to add a border just on the top side of a UIView

My question is on the title. I don't know how to add a border in a specific side, top or bottom, any side... layer.border draws the border for the whole view...

stackoverflow.com

https://developer.apple.com/documentation/uikit/uiview/1622559-autoresizingmask

 

Apple Developer Documentation

 

developer.apple.com