我是iOS开发的新手,我正在与UIStackView
合作。
当我使用StoryBoard
创建两个UILabels
作为UIStackView
的子对象时,下面的代码使每个UILabel
的渐变背景色工作得很好。
UILabel *label;
for (int ii = 1; ii < 3; ii++) {
label = [self.view viewWithTag:ii];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = label.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor yellowColor]CGColor], (id)[[UIColor grayColor]CGColor], nil];
[label.layer insertSublayer:gradient atIndex:0];
UILabel *newLabel = [[UILabel alloc] initWithFrame:label.bounds];
newLabel.backgroundColor = [UIColor clearColor];
newLabel.text = label.text;
[label addSubview:newLabel];
}
但是当我使用下面的代码以编程方式创建两个UILabels
时,我上面为每个UILabel
制作渐变背景的代码不起作用,背景颜色保持白色。
有人能帮我一下吗?
UILabel *myLabel;
myLabel = [[UILabel alloc] init];
[myLabel setText:@"text1"];
[myLabel setTag:1];
[stackView addArrangedSubview:myLabel];
myLabel = [[UILabel alloc] init];
[myLabel setText:@"text2"];
[myLabel setTag:2];
[stackView addArrangedSubview:myLabel];
问题似乎与标签边界有关。下面的代码添加了一个UIStackView和几个带渐变的uilabel。
const int STACK_WIDTH = 200;
const int NUM_LABELS = 3;
const int LABEL_WIDTH = STACK_WIDTH / NUM_LABELS;
UIStackView* stack = [[UIStackView alloc] initWithFrame:CGRectMake(0, 0, STACK_WIDTH, 100)];
stack.axis = UILayoutConstraintAxisHorizontal;
stack.distribution = UIStackViewDistributionFillProportionally;
stack.alignment = UIStackViewAlignmentLeading;
stack.spacing = LABEL_WIDTH;
stack.backgroundColor = [UIColor greenColor];
[self.view addSubview:stack];
for(int i = 0; i < NUM_LABELS; i++){
UIView* myLabelView = [[UIView alloc] initWithFrame:CGRectMake(i * LABEL_WIDTH, 0, LABEL_WIDTH, stack.frame.size.height)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = myLabelView.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor yellowColor]CGColor], (id)[[UIColor grayColor]CGColor], nil];
gradient.startPoint = CGPointMake(0, 0);
gradient.endPoint = CGPointMake(1, 0);
[myLabelView.layer addSublayer:gradient];
UILabel* myLabel = [[UILabel alloc] initWithFrame:myLabelView.bounds];
myLabel.text = [NSString stringWithFormat:@"label: %d", i];
[myLabelView addSubview:myLabel];
[stack addArrangedSubview:myLabelView];
}