Swift UIView边框自定义与Auto Layout适配

为 UIView 添加可选的指定边框(border)并适配 Auto Layout,挺常见的需求。默认情况下,UIView 没有边框,可以通过修改layer.borderWidthlayer.borderColor来为视图加边框。若是只想加某一边的边框,挺,可以通过扩展 UIView 来实现。通过CAShapeLayer,可以根据传入的边界参数(比如上、下、左、右)来定制边框。在layoutSubviews()中确保边框在 Auto Layout 的计算之后被添加,这样就不会影响布局了。

适配 Auto Layout 时,要注意边框宽度的影响。比如视图底部有边框时,底部约束要包括边框宽度,避免内容被遮挡。其实,CALayer 边框有时会增加内存负担,尤其在大量视图的情况下,性能得考虑好。

总结来说,这段代码能帮你实现灵活的边框添加,适配各种屏幕尺寸和方向。实用又不复杂,快去试试吧!

zip
swift-为UIView追加选择指定边的border适配autoLayout.zip 预估大小:20个文件
folder
RITLLayerBorder-master 文件夹
folder
Assets 文件夹
file
PreView.png 43KB
file
.gitignore 1KB
folder
UIView+RITLBorder 文件夹
file
UIView+RITLBorder.h 2KB
file
UIView+RITLBorder.m 9KB
file
README.md 3KB
folder
RITLBorder.xcodeproj 文件夹
folder
project.xcworkspace 文件夹
file
contents.xcworkspacedata 155B
file
project.pbxproj 14KB
folder
xcuserdata 文件夹
folder
yuewen.xcuserdatad 文件夹
folder
xcschemes 文件夹
file
xcschememanagement.plist 333B
folder
xcdebugger 文件夹
file
Breakpoints_v2.xcbkptlist 91B
folder
RITLBorder 文件夹
file
AppDelegate.h 276B
file
ViewController.h 214B
folder
Base.lproj 文件夹
file
Main.storyboard 14KB
file
LaunchScreen.storyboard 2KB
folder
Assets.xcassets 文件夹
folder
AppIcon.appiconset 文件夹
file
Contents.json 1KB
file
main.m 333B
file
Info.plist 1KB
file
AppDelegate.m 2KB
file
ViewController.m 2KB
file
UIView+RITLBorders.podspec 552B
file
LICENSE 1KB
zip 文件大小:49.21KB