【发布时间】:2019-03-12 15:11:52
【问题描述】:
如图所示,我在 XIB 中有一个高度为 800 的自定义视图:
这是层次结构:
这是我的 customView.m 上的代码:
- (id)initWithFrame:(CGRect)frame
{
NSLog(@"initWithFrame");
self = [super initWithFrame:frame];
if (self) {
[self setup];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
NSLog(@"initWithCoder");
self = [super initWithCoder:aDecoder];
if(self) {
[self setup];
}
return self;
}
- (void)setup {
[[NSBundle mainBundle] loadNibNamed:@"customView" owner:self options:nil];
[self addSubview:self.view];
self.view.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, CGRectGetHeight(self.view.frame));
//[self.myscrollview setContentSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width, 2000)];
NSLog(@"contentSize Height :%f", self.myscrollview.contentSize.height);
NSLog(@"contentView Height :%f", self.contentView.frame.size.height);
}
并在我的 viewController 视图上添加自定义视图:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
customView *myView = [[customView alloc] init];
[self.view addSubview:myView];
}
它已加载,但 scrollView 没有滚动。然后我检查 customView 和 contentView 高度,它返回 800,但 scrollView contentSize 高度返回 0。所以我尝试将 contentSize 设置为 2000,但它仍然不滚动。让我感到困惑的是,为什么在我将 scrollView 尾随、前导、底部和顶部 0 设置为 superView 后,它没有跟随 contentView 的高度,而是返回 0。那我应该如何设置 contentSize?
nb: contentView 的高度和宽度等于 superView 并且优先级设置为 250
github:project example
【问题讨论】:
-
当您将其添加为子视图时,为视图添加适当的约束。这将解决您的问题。 stackoverflow.com/questions/35294571/…
-
我没有限制代码。
-
但你应该这样做。你在设计时所拥有的一切都是有约束的。如果你不应用约束来查看添加的运行时,它永远不会给你想要的结果。
标签: ios objective-c uiscrollview autolayout