iOS-UIView的中心内容



我正在尝试创建带有图像和数字的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以按内容动态更改宽度?感谢

我不是在写完整的代码,但您尝试使用以下代码,

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)上,则必须对它们执行相同的操作

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

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

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

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

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

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

可用性在iOS 2.0及更高版本中可用。另请参阅@属性框架@属性界限@属性转换相关示例代码AVLoupe使用应答器方法和手势识别器处理触摸iAdInterstivalSuiteiAdSuiteRosyWriter声明于UIView.h

最新更新