【问题标题】:iOS - center content of UIViewiOS - UIView 的中心内容
【发布时间】:2014-02-24 14:49:02
【问题描述】:

我正在尝试使用图像和数字创建 UIView。我想把它们放在中心。现在我有这个代码:

    CGRect likesRect = CGRectMake(0,152, screenWidth / 2, 30);
    MARoundedRect *likesRoundedRect = [[MARoundedRect alloc] initWithFrame:likesRect];

    UIView *likesView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    likesView.center = CGPointMake(screenWidth / 4, 20);

    UIImageView *likeImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    likeImage.image = [UIImage imageNamed:@"favorite.png"];

    UILabel *likesLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, screenWidth / 2, 20)];
    [likesLabel setTextColor:[UIColor whiteColor]];
    [likesLabel setBackgroundColor: [UIColor clearColor]];
    [likesLabel setText:[actualPlace.Favorites stringValue]];

    [likesView addSubview:likeImage];
    [likesView addSubview:likesLabel];
    [likesRoundedRect addSubview:likesView];
    [viewController.view addSubview:likesRoundedRect];

现在它运行良好,但我将 likesView 的宽度设置为精确值,我想当我没有带有一两个字母但更多的数字时,这会很糟糕。我怎样才能解决这个问题?如果有两个或多个并排的组件,如何使 UIView 的内容居中?或者如何将 UIView 设置为按内容动态更改宽度?谢谢

【问题讨论】:

  • 你可以使用自动布局吗?
  • 我猜是这样,它必须只是在代码中(以编程方式)。

标签: ios objective-c uiview custom-controls


【解决方案1】:

我没有写完整的代码,但你尝试使用以下代码,

CGRect likesRect = CGRectMake(0,152, screenWidth / 2, 30);
MARoundedRect *likesRoundedRect = [[MARoundedRect alloc] initWithFrame:likesRect];

CGSize likeViewSize = CGSizeMake(50,30);
UIView *likesView = [[UIView alloc] init];
likesView.frame = CGRectMake(likesRoundedRect.frame.size.width/2 - likeViewSize.width/2,likesRoundedRect.frame.size.height/2 - likeViewSize.height/2,likeViewSize.width,likeViewSize.height);

我已将likesView 置于其父视图的中心。如果你想将它们放在它们的父视图上,你必须对标签和图像视图做同样的事情 (likesView)

【讨论】:

    【解决方案2】:

    UIView 及其子类有一个名为 center 的属性:

     CGPoint center1 = CGPointmake(self.view.bounds.size.width/2,  
             self.view.bounds.size,height/2) ; 
    
      subview.center = center1;   
    

    以下讨论来自 Apple 关于 UIView 的文档:

    @property(nonatomic) CGPoint 中心 讨论 中心在其父视图的坐标系中指定,并以点为单位进行测量。设置此属性会相应地更改框架属性的值。

    更改框架矩形会自动重新显示接收器,而无需调用 drawRect: 方法。如果您希望在框架矩形更改时调用 drawRect: 方法,请将 contentMode 属性设置为 UIViewContentModeRedraw。

    对此属性的更改可以设置动画。使用 beginAnimations:context: 类方法开始动画块,使用 commitAnimations 类方法结束动画块。

    可用性 在 iOS 2.0 及更高版本中可用。 也可以看看 @property 框架 @property 边界 @property 转换 相关示例代码 AVLoup 使用响应器方法和手势识别器处理触摸 iAdInterstitialSuite 广告套件 玫瑰色作家 宣布于 UIView.h

    【讨论】:

      猜你喜欢
      • 2013-07-22
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多