Thursday, February 21, 2019

Make borde part of view Swift

To make border entire of view, we use
view.layer.borderWidth=1
Nhưng nếu chỉ muốn viền một phía nào đó thì hãy tạo một class riêng, copy các dòng sau vào
If we just want border some part of view, create a new class like this.
import Foundation
import UIKit
extensionCALayer {
func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
let border = CALayer()
switch edge {
caseUIRectEdge.Top:
   border.frame = CGRectMake(0, -thickness, CGRectGetWidth(self.frame), thickness)
break
caseUIRectEdge.Bottom:
  border.frame = CGRectMake(0, CGRectGetHeight(self.frame), CGRectGetWidth(self.frame), thickness)
break
caseUIRectEdge.Left:
  border.frame = CGRectMake(-thickness, 0, thickness, CGRectGetHeight(self.frame))
break
caseUIRectEdge.Right:
 border.frame = CGRectMake(CGRectGetWidth(self.frame), 0, thickness, CGRectGetHeight(self.frame))
break
default:
break
        }
border.backgroundColor = color.CGColor;
self.addSublayer(border)
   }
}
Now, in any class, use command like this.
la.layer.addBorder(UIRectEdge.Right, color: UIColor.blackColor(), thickness: 0.5)
la.layer.addBorder(UIRectEdge.Top, color: UIColor.blackColor(), thickness: 0.5)
la.layer.addBorder(UIRectEdge.Bottom, color: UIColor.blackColor(), thickness: 0.5)
la.layer.addBorder(UIRectEdge.Left, color: UIColor.blackColor(), thickness: 0.5)
Change long and thickness border in  case extension if you want.
Another way, for example, border left.
var border = CALayer()
border.backgroundColor = UIColor.redColor().CGColor
border.frame = CGRect(x: -1, y: 0, width: 1.0, height: la.frame.height)
label.layer.addSublayer(border)
Border right, change line three to
border.frame = CGRect(x: label.frame.width, y: 0, width: 1.0, height: label.frame.height)
Border top, change line three to
border.frame = CGRect(x: -1, y: -1, width: label.frame.width, height: 1)
Border bottom, change line three to

border.frame = CGRect(x: 0, y: label.frame.height, width: label.frame.width, height: 1)



No comments:

Post a Comment