简体   繁体   中英

UIButton added as subview is away from UIView

Tried and searched a lot. Button added as subview is away from view when the frame of superview is small. I dont want it to be appear when frame is small.

 UIView *vw = [[UIView alloc] initWithFrame:CGRectMake(20 , 100, 200, 30)];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    [btn setTitle:@"OK" forState:UIControlStateNormal];
    [btn setFrame:CGRectMake(20 , 100, 30, 20)];
    [vw sendSubviewToBack:btn];
    [vw addSubview:btn];
    [vw setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:vw];

this is my code. It look like this

在此输入图像描述

Look on the frame of the UIButton. Its origin.y is 100px. It should be 0, if you want to add it to the vw.

You did wrong. Before adding btn to view, you've called sendSubviewToBack: . Just rewrite as below.

[vw addSubview:btn];//First
[self.view addSubview:vw];//second
[vw sendSubviewToBack:btn];//Third

You don't want to appear if it's lie outside superview, use this. vw.clipsToBounds = YES

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM