在UIStackView中将UILabel的背景更改为渐变颜色

时间:2016-07-03 09:15:48

标签: ios iphone uistackview

我是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];

1 个答案:

答案 0 :(得分:0)

问题似乎与标签边界有关。下面的代码添加了一个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];
}