Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 使用自动布局将UILabel放置在UIView旁边_Ios_Objective C_Autolayout - Fatal编程技术网

Ios 使用自动布局将UILabel放置在UIView旁边

Ios 使用自动布局将UILabel放置在UIView旁边,ios,objective-c,autolayout,Ios,Objective C,Autolayout,我想将UIView水平放置在UILabel的右侧。UILabel的宽度可变,具体取决于其中的文本。以图形方式: |这是我的观点| |这是一篇长篇大论|我的观点| 您能告诉我如何使用自动布局以编程方式创建此接口吗 我有这个: self.myLabel = [[[UILabel alloc] init] autorelease]; self.myView = [[[UIView alloc] init] autorelease]; [self addSubview:self.myLabel]; [

我想将UIView水平放置在UILabel的右侧。UILabel的宽度可变,具体取决于其中的文本。以图形方式:

|这是我的观点|

|这是一篇长篇大论|我的观点|

您能告诉我如何使用自动布局以编程方式创建此接口吗

我有这个:

self.myLabel = [[[UILabel alloc] init] autorelease];
self.myView = [[[UIView alloc] init] autorelease];

[self addSubview:self.myLabel];
[self addSubview:self.myLabel];
但是现在我需要自动布局约束来将
myView
放置在
myLabel
的右侧,并使
myLabel
的宽度适合它包含的文本。你知道这是怎么做到的吗


感谢您的帮助。

您可以使用sizeToFit为UILabel设置动态宽度

之后,您将获得帧的最大x

CGRectGetMaxX(self.myLabel.frame)
因此,如果要将视图放置在标签旁边,请将视图的框架设置为

self.myView.frame = CGRectMake(CGRectGetMaxX(self.myLabel.frame)+10, y, WIDTH, HEIGHT);

假设它是一个具有固定行数的标签,它知道自己的宽度,您不必专门设置它。水平布置它们的约束条件如下

NSMutableDictionary viewsDictionary = [[NSMutableDictionary alloc] initWithObjects:@[self.myLabel, self.myView] forKeys:@[@"mylabel", @"myview"]];
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[mylabel]-[myview]" options:0 metrics:nil views:viewsDictionary];

此约束仅指定水平布局。要做到这一点,您还必须指定垂直位置,以便约束系统能够准确地确定视图的位置。

自动布局约束不适合您的标签宽度和文本大小。您需要使用上面的方法来实现这一点
NSMutableDictionary viewsDictionary = [[NSMutableDictionary alloc] initWithObjects:@[self.myLabel, self.myView] forKeys:@[@"mylabel", @"myview"]];
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[mylabel]-[myview]" options:0 metrics:nil views:viewsDictionary];