我也做了同样的事UIView
类别。这是我的方法:
#define SEPARATOR_HEIGHT 0.5
- (void)addSeparatorLinesWithColor:(UIColor *)color
{
[self addSeparatorLinesWithColor:color edgeInset:UIEdgeInsetsZero];
}
- (void)addSeparatorLinesWithColor:(UIColor *)color edgeInset:(UIEdgeInsets)edgeInset
{
UIView *topSeparatorView = [[UIView alloc] initWithFrame:CGRectMake(edgeInset.left, - SEPARATOR_HEIGHT, self.frame.size.width - edgeInset.left - edgeInset.right, SEPARATOR_HEIGHT)];
[topSeparatorView setBackgroundColor:color];
[self addSubview:topSeparatorView];
UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(edgeInset.left, self.frame.size.height + SEPARATOR_HEIGHT, self.frame.size.width - edgeInset.left - edgeInset.right, SEPARATOR_HEIGHT)];
[separatorView setBackgroundColor:color];
[self addSubview:separatorView];
}
只是为了补充雷米的精彩答案,这样做可能更简单。制作一个类 UILine.m
@interface UILine:UIView
@end
@implementation UILine
-(id)awakeFromNib
{
// careful, contentScaleFactor does NOT WORK in storyboard during initWithCoder.
// example, float sortaPixel = 1.0/self.contentScaleFactor ... does not work.
// instead, use mainScreen scale which works perfectly:
float sortaPixel = 1.0/[UIScreen mainScreen].scale;
UIView *topSeparatorView = [[UIView alloc] initWithFrame:
CGRectMake(0, 0, self.frame.size.width, sortaPixel)];
topSeparatorView.userInteractionEnabled = NO;
[topSeparatorView setBackgroundColor:self.backgroundColor];
[self addSubview:topSeparatorView];
self.backgroundColor = [UIColor clearColor];
self.userInteractionEnabled = NO;
}
@end
在 IB 中,放入 UIView,单击 Identity Inspector 并将该类重命名为 UILine。设置width你想在IB。将高度设置为 1 或 2 像素 - 只是这样您就可以在 IB 中看到它。设置背景色你想在IB。当您运行该应用程序时,它将变成一条 1 像素的线、该宽度、该颜色。 (您可能不应该受到 Storyboard/xib 中任何默认自动调整大小设置的影响,我无法让它中断。)您已经完成了。
注意:你可能会想“为什么不直接调整 UIView 的大小在 awakeFromNib 的代码中?”在故事板应用程序中加载时调整视图大小是有问题的 - 请参阅此处有关它的许多问题!
有趣的问题:您可能只是将 UIView 在故事板上设置为 10 或 20 像素高,这样您就可以看到它。当然,它会在应用程序中消失,您会得到漂亮的一根像素线。但!一定要记住self.userInteractionEnabled = NO
,或者它可能会超越您的其他按钮!
2016解决方案!https://stackoverflow.com/a/34766567/294884 https://stackoverflow.com/a/34766567/294884