2014-02-24 68 views
0

我想创建具有图像和编号的UIView。我想集中他们。现在我有这样的代码:iOS - 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动态改变宽度的内容?由于

+0

您能使用自动布局? – Wain

+0

我想是的,它只能在代码中(以编程方式)。 –

回答

0

我不写完整代码,但你尝试用下面的代码,

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); 

我都集中在其parentview的likesView。你必须做同样的事情标签和ImageView的,如果你要居中他们在他们的parentview(likesView

0

的UIView和它的子类有一个属性叫做中心:

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

    subview.center = center1; 

下面的讨论是从Apple关于UIView的文档:

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

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

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

供货情况 适用于iOS 2.0及更高版本。 请参见 @property框架 @property界 @property变换 关联的例子代码 AVLoupe 处理倒是采用响应的方法和姿势识别 iAdInterstitialSuite iAdSuite RosyWriter 宣布 UIView.h