Ios 在UIView上尝试圆角时的奇怪行为
我在Swift3中的UIView中与一种奇怪的行为斗争了好几个小时。我只是想在屏幕中间添加一个UIView,带有彩色和圆形边框 为了方便地绕过边界,我使用以下扩展:Ios 在UIView上尝试圆角时的奇怪行为,ios,swift,uiview,border,Ios,Swift,Uiview,Border,我在Swift3中的UIView中与一种奇怪的行为斗争了好几个小时。我只是想在屏幕中间添加一个UIView,带有彩色和圆形边框 为了方便地绕过边界,我使用以下扩展: extension UIView { /** Rounds the given set of corners to the specified radius - parameter corners: Corners to round - parameter radius: Radius to round to */
extension UIView {
/**
Rounds the given set of corners to the specified radius
- parameter corners: Corners to round
- parameter radius: Radius to round to
*/
func round(corners: UIRectCorner, radius: CGFloat) {
_round(corners: corners, radius: radius)
}
/**
Rounds the given set of corners to the specified radius with a border
- parameter corners: Corners to round
- parameter radius: Radius to round to
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
func round(corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
let mask = _round(corners: corners, radius: radius)
addBorder(mask: mask, borderColor: borderColor, borderWidth: borderWidth)
}
/**
Fully rounds an autolayout view (e.g. one with no known frame) with the given diameter and border
- parameter diameter: The view's diameter
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
func fullyRound(diameter: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
layer.masksToBounds = true
layer.cornerRadius = diameter / 2
layer.borderWidth = borderWidth
layer.borderColor = borderColor.cgColor;
}
}
private extension UIView {
@discardableResult func _round(corners: UIRectCorner, radius: CGFloat) -> CAShapeLayer {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
return mask
}
func addBorder(mask: CAShapeLayer, borderColor: UIColor, borderWidth: CGFloat) {
let borderLayer = CAShapeLayer()
borderLayer.path = mask.path
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.strokeColor = borderColor.cgColor
borderLayer.lineWidth = borderWidth
borderLayer.frame = bounds
layer.addSublayer(borderLayer)
}
}
class GameViewController: UIViewController {
@IBOutlet weak var cardView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
cardView.round(corners: UIRectCorner.allCorners, radius: 5.0, borderColor: DesignHelper.defaultColor, borderWidth: 1)
}
}
我只是使用正确的参数调用myView.round(),但它没有按预期工作
有什么建议吗 实际上,我在UIViewController的viewDidLoad中调用round方法。然而,正如@luk2302所注意到的,这不是处理边界、框架等的正确位置,因为此时视图没有完全加载
因此,我将对round方法的调用移动到UIViewController的ViewDidLayoutSubView方法中。那很好 您在视图生命周期的什么时候调用
addBorder
?可能在布局信息尚未呈现的某个时间,方法round调用方法addBorder。通常,当调用addBorder时,掩码已经创建,正如您在代码I postedcheck中看到的,当调用round方法时检查视图的边界Kay,当调用round
时?基本上,您发布的任何代码何时从实际的viewcontroller内部调用?@ReinierMelian我已经检查过了,当调用round方法时,UIView的边界是正确的。