有没有一种方法可以将UIView的边框设置为一种颜色,而让顶部和底部保持另一种颜色?
发布于 2015-06-17 02:29:55
与边框一样工作的视图的答案是非常好的,但请记住,每个视图都是一个耗费大量内存的UI对象。
我将使用uivew的层在已经存在的UIview上绘制一个带有颜色的笔划。
-(CAShapeLayer*)drawLineFromPoint:(CGPoint)fromPoint toPoint:(CGPoint) toPoint withColor:(UIColor *)color andLineWidth:(CGFloat)lineWidth{
CAShapeLayer *lineShape = nil;
CGMutablePathRef linePath = nil;
linePath = CGPathCreateMutable();
lineShape = [CAShapeLayer layer];
lineShape.lineWidth = lineWidth;
lineShape.strokeColor = color.CGColor;
NSUInteger x = fromPoint.x;
NSUInteger y = fromPoint.y;
NSUInteger toX = toPoint.x;
NSUInteger toY = toPoint.y;
CGPathMoveToPoint(linePath, nil, x, y);
CGPathAddLineToPoint(linePath, nil, toX, toY);
lineShape.path = linePath;
CGPathRelease(linePath);
return lineShape;}
并将其添加到我们的视图中。
CAShapeLayer* borderLine=[self drawLineFromPoint:CGPointMake(0, 0) toPoint:CGPointMake(0,_myView.frame.size.height) withColor:[UIColor lightGrayColor] andLineWidth:1.0f];
[_myView.layer addSublayer:borderLine];
所以..。我们取一个点,从视图的顶部到底部绘制一条线。结果是有一条线条看起来像一个像素宽度的边框。
发布于 2016-04-07 03:39:24
针对Swift 3.0更新
我写了一个Swift扩展(针对UIButton),它模拟将UIView任意一侧的边框设置为给定的颜色和宽度。它类似于@Noah Witherspoon的方法,但基于自包含和自动布局约束。
// Swift 3.0
extension UIView {
enum Border {
case left
case right
case top
case bottom
}
func setBorder(border: UIView.Border, weight: CGFloat, color: UIColor ) {
let lineView = UIView()
addSubview(lineView)
lineView.backgroundColor = color
lineView.translatesAutoresizingMaskIntoConstraints = false
switch border {
case .left:
lineView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
lineView.topAnchor.constraint(equalTo: topAnchor).isActive = true
lineView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
lineView.widthAnchor.constraint(equalToConstant: weight).isActive = true
case .right:
lineView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
lineView.topAnchor.constraint(equalTo: topAnchor).isActive = true
lineView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
lineView.widthAnchor.constraint(equalToConstant: weight).isActive = true
case .top:
lineView.topAnchor.constraint(equalTo: topAnchor).isActive = true
lineView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
lineView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
lineView.heightAnchor.constraint(equalToConstant: weight).isActive = true
case .bottom:
lineView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
lineView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
lineView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
lineView.heightAnchor.constraint(equalToConstant: weight).isActive = true
}
}
}
发布于 2012-06-28 08:41:29
这听起来像是两个答案中的一个:
如果你的视图是静态大小的,那么只需在它后面放置一个比前视图宽2像素、短2像素的UIView即可。
如果它是非静态大小的,那么您可以执行相同的操作,在调整前景视图大小时调整背景视图的大小,或者实现一个实现UIView的自定义对象,并实现(覆盖)您自己的drawRect例程。
https://stackoverflow.com/questions/11236607
复制相似问题