Emre O. Emre O. - 3 months ago 43
Objective-C Question

Copying UIButtons frame gives wrong position

I want to create another UIView / UIButton on an UIButton so I'm getting its' frame and use it in declaration of another UIView but It creates like below screenshot (with blue view). By the way, button is created on storyboard.

I'm using Xcode 9.1 and iOS 11.1

- (void)viewDidLoad {

UIView *picker = [[UIView alloc] initWithFrame:_mButton.frame];
picker.backgroundColor=[UIColor blueColor];
[self.view addSubview: picker];

Screenshot 1
Screnshot 2

Answer Source

I guess the proper frames are not calculated in viewDidLoad. You can try to make picker a property and adjust its frame in viewDidLayoutSubviews

@property (strong, nonatomic) UIView *picker;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.picker = [[UIView alloc] initWithFrame:_mButton.frame];
    self.picker.backgroundColor=[UIColor blueColor];
    [self.view addSubview: self.picker];

- (void)viewDidLayoutSubviews {
    self.picker.frame = _mButton.frame;
    [super viewDidLayoutSubviews];

But off course using storyboard and autolayout would probably be the best sollution if you have this possibility.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download