有没有一种方法可以将UIView的边框的边设置为一种颜色,而将顶部和底部保留为另一种颜色?
最佳答案
不,CALayer边界不支持这种行为。完成所需操作的最简单方法是,在 View 的每一侧添加一个n点宽的不透明 subview ,并将所需的边框颜色作为其背景色。
例:
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边界的行为完全不符-左边界 View 和右边界 View 将始终位于其 super View 的边界之内。