ios - 在 UIView 上绘制顶线和底线

标签 ios objective-c uiview

我正在尝试在 UIView 的顶部和底部边缘绘制线条。但这条线并没有一直绘制到 View Controller 的右边缘。

以下是我用来绘制线条的代码:

- (void)addBorders
{
    CALayer *upperBorder = [CALayer layer];
    CALayer *bottomBorder = [CALayer layer];
    upperBorder.backgroundColor = [[UIColor colorWithRed:225/255.0 green:220/255.0 blue:214/255.0 alpha:1.0f] CGColor];
    upperBorder.frame = CGRectMake(0, 0, CGRectGetWidth(self.recentTuneinView.frame), 0.5f);
    bottomBorder.backgroundColor = [[UIColor colorWithRed:154/255.0 green:154/255.0 blue:154/255.0 alpha:1.0f] CGColor];
    bottomBorder.frame = CGRectMake(0, 58.0f, CGRectGetWidth(self.recentTuneinView.frame), 0.5f);
    [self.recentTuneinView.layer addSublayer:upperBorder];
    [self.recentTuneinView.layer addSublayer:bottomBorder];

}

这是显示问题的图像:

enter image description here

代码中我缺少什么?

谢谢。

最佳答案

添加子图层不是一个可扩展的解决方案,因为它会在旋转设备或 View 大小更改时产生问题。

我的建议是创建一个自定义 View 并实现drawRect:,如下所示:

- (void)drawRect:(CGRect)iRect {
    CGContextRef aContext = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(aContext, 0.5);

    // Set Top Line Color
    CGContextSetStrokeColorWithColor(aContext, [[UIColor colorWithRed:225/255.0 green:220/255.0 blue:214/255.0 alpha:1.0f] CGColor]);

    // Top Line
    CGContextMoveToPoint(aContext, 0, 0);
    CGContextAddLineToPoint(aContext, iRect.size.width, 0);

    // Set Bottom Line Color
    CGContextSetStrokeColorWithColor(aContext, [[UIColor colorWithRed:225/255.0 green:220/255.0 blue:214/255.0 alpha:1.0f] CGColor]);

    // Bottom Line
    CGContextMoveToPoint(aContext, 0, 58.0);
    CGContextAddLineToPoint(aContext, iRect.size.width, 58.0);
}

关于ios - 在 UIView 上绘制顶线和底线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33172607/

相关文章:

ios - 无法从 pod 框架内部登录

objective-c - 如何将数据从 native react 传递到 native iOS View ?

ios - 如何根据其内容增加 XIB View ?

ios - 在等待主视图加载时显示 UIView?

ios - 为什么按钮图像被压缩?

ios - 如何访问多级结构化 Plist

ios - 如何从ios中的raw中以漂亮的方式打印响应请求

ios - 限制 subview 在父 View 范围内的移动

ios - 如何在 UIScrollView 的 super View 中检测 "Touch Down"?

ios - MKMapView - 将 map 滚动限制为方形覆盖