UIView 只设置侧边框 [英] UIView set only side borders

查看:23
本文介绍了UIView 只设置侧边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将 UIView 的边框的边设置为一种颜色,而将顶部和底部保留另一种颜色?

Is there a way to set the sides of the border of a UIView to one color and leave the top and the bottom another?

推荐答案

不——CALayer 边框不支持这种行为.实现您想要的最简单的方法是添加一个 n 点宽的不透明子视图,并在视图的每一侧添加您想要的边框颜色作为其背景颜色.

Nope—CALayer borders don’t support that behavior. The easiest way to accomplish what you want is adding an n-point-wide opaque subview with your desired border color as its background color on each side of your view.

示例:

CGSize mainViewSize = theView.bounds.size;
CGFloat borderWidth = 2;
UIColor *borderColor = [UIColor redColor];
UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, borderWidth, mainViewSize.height)];
UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(mainViewSize.width - borderWidth, 0, borderWidth, mainViewSize.height)];
leftView.opaque = YES;
rightView.opaque = YES;
leftView.backgroundColor = borderColor;
rightView.backgroundColor = borderColor;

// for bonus points, set the views' autoresizing mask so they'll stay with the edges:
leftView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin;
rightView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin;

[theView addSubview:leftView];
[theView addSubview:rightView];

[leftView release];
[rightView release];

请注意,这与 CALayer 边框的行为不太匹配——左右边框视图将始终位于其父视图的边界内.

Note that this won’t quite match the behavior of CALayer borders—the left and right border views will always be inside the boundaries of their superview.

这篇关于UIView 只设置侧边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆