Search code examples
iosiphoneobjective-csubviewcgrectmake

Programmatically create subview that covers the top 50% of the iPhone screen


I have a subview and I have been customizing its size by using the frame property and setting its value to the CGRectMake function's parameter values.

I have slowly but surely been changing the CGRectMake parameters and re-running the app to get the subview to the correct position on the screen but I know there has to be an easier way.

Here is what I am currently doing:

UIImageView *halfView = [[UIImageView alloc]initWithImage:image];

[self.view addSubview:halfView];

halfView.frame = CGRectMake(0, 0, 320, 270);

Is there a way that I can stop having to manually enter those 4 parameters into CGRectMake, and just set it to the top 50% of the screen?

Here is what I want the subview to look like on the iphone's screen:

enter image description here


Solution

  • halfView.frame = CGRectMake(0, 0, 320, self.view.bounds.size.height/2);
    

    you just take the height and divide it by two

    You should also probably change 320 to self.view.bounds.size.width

    I suggest reading this post to really get a grasp of UIViews and working with them: UIView frame, bounds and center