ios 有没有办法在界面构建器中制作渐变背景色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8164609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:26:12  来源:igfitidea点击:

Is there a way to make gradient background color in the interface builder?

iosuitableviewinterface-builder

提问by Serdar Dogruyol

For my application I'm using a TableView and using customized UITableViewCells.

对于我的应用程序,我使用的是 TableView 并使用自定义的 UITableViewCells。

I customized my cells via interface builder, not programmatically. Is there a way to also make the background color of my customized cell a gradient in the interface builder?

我通过界面构建​​器而不是编程方式自定义了我的单元格。有没有办法让我的自定义单元格的背景颜色在界面构建器中成为渐变?

Thanks.

谢谢。

采纳答案by Aberrant

To draw a gradient, you will have to subclass and override the drawRect programmatically:

要绘制渐变,您必须以编程方式子类化并覆盖 drawRect:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents
                             (colorSpace,
                              (const CGFloat[8]){1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f},
                              (const CGFloat[2]){0.0f,1.0f},
                              2);

    CGContextDrawLinearGradient(context,
                                gradient,
                                CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMinY(self.bounds)),
                                CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMaxY(self.bounds)),
                                0);

    CGColorSpaceRelease(colorSpace);
    CGContextRestoreGState(context);
}

The easiestway, which keeps your cells in the interface builder, is probably to subclass a UIView to have it draw a gradient in its drawRect and place it in your cell behind the other subviews:

将单元格保留在界面构建器中的最简单方法可能是将 UIView 子类化,使其在其 drawRect 中绘制渐变并将其放置在其他子视图后面的单元格中:

GradientView *gradientView = [[GradientView alloc] init];
gradientView.frame = cell.bounds;
[cell addSubview:gradientView];
[cell sendSubviewToBack:gradientView];

However, the bestway to do it is probably not to use the interface builder for this and make a subclass of UITableViewCell. For advanced customization, interface builders tend to only make things more complicated in my experience. That's up to personal preference though.

但是,最好的方法可能是不要为此使用界面构建器并创建 UITableViewCell 的子类。对于高级定制,根据我的经验,界面构建器往往只会让事情变得更加复杂。不过这也看个人喜好了。

回答by etayluz

This works for Swift 3.0: (Updated for Swift 4.0)

这适用于 Swift 3.0:(已针对 Swift 4.0 更新)

@IBDesignable
final class GradientView: UIView {
    @IBInspectable var startColor: UIColor = UIColor.clear
    @IBInspectable var endColor: UIColor = UIColor.clear

    override func draw(_ rect: CGRect) {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = CGRect(x: CGFloat(0),
                                y: CGFloat(0),
                                width: superview!.frame.size.width,
                                height: superview!.frame.size.height)
        gradient.colors = [startColor.cgColor, endColor.cgColor]
        gradient.zPosition = -1
        layer.addSublayer(gradient)
    }
}

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

回答by Ali Raza

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = yourView.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)    [[UIColor whiteColor] CGColor], nil];
[yourView.layer insertSublayer:gradient atIndex:0];

回答by Sudesh Kumar

Yes this is possible : Make a image in gradient with 1 X Height pix. Set this to backgroundColor for cell.

是的,这是可能的:使用 1 X 高度像素以渐变方式制作图像。将此设置为单元格的背景颜色。

cell.backgroundColor =  [UIColor colorWithPatternImage:[UIImage imageNamed:@"gradImage.png"]];

**You can set gradient color with code but its time taken process. If you fill better then search for that.

**您可以使用代码设置渐变颜色,但需要花费时间。如果你填得更好,然后搜索那个。

回答by alfhern

answer by etayluzworks fine but I added a couple changes:

etayluz 的回答工作正常,但我添加了一些更改:

  1. Gradient size defined by own layer bounds, not the superview.
  2. Remove Gradient layer on every draw, so that it does not keep drawing and adding a new layer when redraw is necessary (for instance by calling .setNeedsDisplay()on rotation).

    @IBDesignable final class MFGradientView: UIView {
    
        @IBInspectable var startColor: UIColor = UIColor.clear
        @IBInspectable var endColor: UIColor = UIColor.clear
    
        override func draw(_ rect: CGRect) {
           layer.sublayers?.first?.removeFromSuperlayer()
    
           let gradient: CAGradientLayer = CAGradientLayer()
           gradient.frame = CGRect(origin: CGPoint.zero, size: self.bounds.size)
           gradient.colors = [startColor.cgColor, endColor.cgColor]
           layer.insertSublayer(gradient, at: 0)
        }
    } 
    
  1. 由自己的层边界定义的渐变大小,而不是父视图。
  2. 在每次绘制时删除渐变图层,以便在需要重绘时(例如通过调用.setNeedsDisplay()旋转)不会继续绘制和添加新图层。

    @IBDesignable final class MFGradientView: UIView {
    
        @IBInspectable var startColor: UIColor = UIColor.clear
        @IBInspectable var endColor: UIColor = UIColor.clear
    
        override func draw(_ rect: CGRect) {
           layer.sublayers?.first?.removeFromSuperlayer()
    
           let gradient: CAGradientLayer = CAGradientLayer()
           gradient.frame = CGRect(origin: CGPoint.zero, size: self.bounds.size)
           gradient.colors = [startColor.cgColor, endColor.cgColor]
           layer.insertSublayer(gradient, at: 0)
        }
    } 
    

回答by JulianM

Based on etayluz answer I changed the code a little bit by taking the layerClassproperty of a UIViewinto account, so you do not need a separate layer as a sublayer.

基于 etayluz 的回答,我通过考虑UIViewlayerClass属性对代码进行了一些更改,因此您不需要单独的图层作为子图层。

I think it is much cleaner and it also works with live updates in the Interface Builder.

我认为它更干净,而且它也适用于 Interface Builder 中的实时更新。

@IBDesignable final class GradientView: UIView {

    @IBInspectable var startColor: UIColor = UIColor.red
    @IBInspectable var endColor: UIColor = UIColor.blue

    override class var layerClass: AnyClass {
        get {
            return CAGradientLayer.self
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupGradient()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupGradient()
    }

    private func setupGradient() {
        let gradient = self.layer as! CAGradientLayer
        gradient.colors = [startColor.cgColor, endColor.cgColor]
    }

}

回答by LLIAJLbHOu

Create a simple view class with @IBInspectable properties.

使用@IBInspectable 属性创建一个简单的视图类。

  1. Create gradient layer once
  2. Reuse gradient layer each layout subviews
  1. 一次创建渐变层
  2. 重用渐变层每个布局子视图

...

...

//
//  GradientView.swift
//
//  Created by Maksim Vialykh on 23.08.2018.
//  Copyright ? 2018 Vialyx. All rights reserved.
//

import UIKit

class GradientView: UIView {

    @IBInspectable
    var startColor: UIColor = .white

    @IBInspectable
    var endColor: UIColor = .black

    private let gradientLayerName = "Gradient"

    override func layoutSubviews() {
        super.layoutSubviews()

        setupGradient()
    }

    private func setupGradient() {
        var gradient: CAGradientLayer? = layer.sublayers?.first { ##代码##.name == gradientLayerName } as? CAGradientLayer
        if gradient == nil {
            gradient = CAGradientLayer()
            gradient?.name = gradientLayerName
            layer.addSublayer(gradient!)
        }
        gradient?.frame = bounds
        gradient?.colors = [startColor.cgColor, endColor.cgColor]
        gradient?.zPosition = -1
    }

}

回答by TigerCoding

I don't know if there is a gradient option, but you could add an UIImageView to the custom cell and add an image with a gradient.

我不知道是否有渐变选项,但您可以向自定义单元格添加 UIImageView 并添加带有渐变的图像。

回答by Gargolev

No, you can't. You could use UISegmentedControl with one segment in older sdk and xCode versions: http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/But now you can't make less than two segments in one UISegmentedControl. And even this way you couldn't change the default colors of the buttons without coding.

不,你不能。您可以将 UISegmentedControl 与较旧的 sdk 和 xCode 版本中的一个段一起使用:http: //chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/但现在你不能在一个 UISegmentedControl 中制作少于两个段。即使这样,您也无法在不编码的情况下更改按钮的默认颜色。