如何在iOS中更改自定义UIView的大小

时间:2016-04-29 11:49:41

标签: ios objective-c constraints

我想在视图控制器的底部使用自定义视图作为工具栏,然后以我自己的方式设计它。我正在使用UIView用于此目的,然后添加为子视图。不知何故,我的自定义工具栏的高度没有变化。甚至,我关闭它的约束,但不知何故,它自动调整。我怎样才能做到这一点?以下是我的代码段。

//CameraActivity.h class
@interface CameraActivity : UIViewController

//Custom UIView.
@property (nonatomic, strong) UIView *toolbar;

@end

//CameraActivity.m class, in viewDidLoad.

_toolbar.translatesAutoresizingMaskIntoConstraints = YES;
    [self.view removeConstraints:self.view.constraints];
    [_toolbar removeConstraints:_toolbar.constraints];
    CGRect frame = CGRectMake(0, [[UIScreen mainScreen] bounds].size.height - 44, [[UIScreen mainScreen] bounds].size.width, 150);
    _toolbar = [[UIView alloc]initWithFrame:frame];
    [_toolbar setBackgroundColor:[UIColor colorWithRed:116.0/255.0 green:174.0/255.0 blue:220.0/255.0 alpha:0.75]];

    [self.view addSubview:_toolbar];

3 个答案:

答案 0 :(得分:0)

在创建(_toolbar = [[UIView alloc]initWithFrame:frame];)您的观看toolbar之前,使用它会导致此问题。

因此,将行顺序更改为:

 CGRect frame = CGRectMake(0, [[UIScreen mainScreen] bounds].size.height - 44, [[UIScreen mainScreen] bounds].size.width, 150);
_toolbar = [[UIView alloc]initWithFrame:frame];
_toolbar.translatesAutoresizingMaskIntoConstraints = YES;
[self.view removeConstraints:self.view.constraints];
[_toolbar removeConstraints:_toolbar.constraints];
[_toolbar setBackgroundColor:[UIColor colorWithRed:116.0/255.0 green:174.0/255.0 blue:220.0/255.0 alpha:0.75]];
[self.view addSubview:_toolbar];

另外我建议设置框架必须完成     -(void) viewDidLayoutSubviews因为viewDidLoad不是一个好地方!所以,

-(void) viewDidLayoutSubviews 
{
 _toolbar.frame  = CGRectMake(0, [[UIScreen mainScreen] bounds].size.height - 44, [[UIScreen mainScreen] bounds].size.width, 150);

}

答案 1 :(得分:0)

我从对象库中添加了UIView,而不是以编程方式添加它,然后根据设备的屏幕宽度和高度将其宽度设置为常量。还分配了一些约束来解决我的问题。 Constraints need to be set

//CameraActivity.h class
@interface CameraActivity : UIViewController

//This time not custom UIView but IBOutlet.
@property (nonatomic, strong) IBOutlet UIView *toolbar;

@end

//CameraActivity.m class
#import "CameraActivity.h"
@implementation CameraActivity

-(void)viewDidLoad
{
    [super viewDidLoad];
    //Get your device screen width.
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    _toolbar.frame = CGRectMake(0, 44, width, 150);
}

答案 2 :(得分:0)

制作UIView身高限制的出口。然后尝试根据设备的类型更改其高度,如下所示: -

ViewController.h文件中,创建一个插座: -

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *viewHeightConstraint;

ViewController.m文件中,更改您的身高约束: -

if (Device is iPhone 4s) {
    viewHeightConstraint.constant = 30.0;  //Your desired height
}
else if (Device is iPhone 5 || Device is iPhone 5s || Device is iPhone 5c) {
   viewHeightConstraint.constant = 40.0;  //Your desired height
}
else if (Device is iPhone 6) {
   viewHeightConstraint.constant = 50.0;  //Your desired height
}
else if (Device is iPhone 6 Plus) {
   viewHeightConstraint.constant = 60.0;  //Your desired height
}

快乐编码!!