用不同的色的背景的文本

时间:2016-12-06 10:59:30

标签: ios

如何在iOS中实现以下设计,是可用于实现此目的的任何控件。我在原生中实现这种设计并不是那么有经验。是使用本机还是采用混合技术开发的

请查看以下图片以供参考

Sample image

1 个答案:

答案 0 :(得分:0)

我为你制作了一个程序化的例子(种类为“Hello World”) (这是编程的原因,我相信它更容易理解事情是如何运作的。 这不是完美的解决方案,它可以做得更好,(性能明智),但我选择它作为一个简单的例子让你开始(我个人会用CALayer作为背景)。

所以这里:

按如下方式创建一个新类:

MyView.h

#import <UIKit/UIKit.h>

@interface MyView : UIView

@end

MyView.m

#import "MyView.h"

@implementation MyView

- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        self.backgroundColor = [UIColor grayColor];

        //This rect is in self coordinate system
        UIView * viewPurple = [[UIView alloc]initWithFrame:CGRectMake(0, 200, frame.size.width, 50)];
        viewPurple.backgroundColor = [UIColor purpleColor];
        [self addSubview:viewPurple];

        //This rect is in viewPurple's coordinate system
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, frame.size.width/2, 50)];
        [label setText:@"Hello World!"];
        [label setTextAlignment:(NSTextAlignmentCenter)];
        [label setTextColor:[UIColor whiteColor]];
        [viewPurple addSubview:label];

        //All the frame's rects are in it's `superView`/ parent 's coordinate system.


        UIView * viewGreen = [[UIView alloc]initWithFrame:CGRectMake(frame.size.width/2, 200, frame.size.width, 50)];
        viewGreen.backgroundColor = [UIColor cyanColor];
        [self addSubview:viewGreen];

        UILabel * label2 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, frame.size.width/2, 50)];
        [label2 setText:@"World Hello!"];
        [label2 setTextAlignment:(NSTextAlignmentCenter)];
        [label2 setTextColor:[UIColor whiteColor]];
        [viewGreen addSubview:label2];

    }
    else
    {
        //Can't allocate the UIView - quite a rare problem.
    }
    return self;
}

@end
视图控制器中的

#import "myView.h"

并将此代码段添加到- (void)viewDidLoad方法。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    MyView * view = [[MyView alloc]initWithFrame:self.view.frame];
    [self.view addSubview:view];
}

结果如下

enter image description here