简体   繁体   English

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

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

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. 谢谢。

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)
    }
}

在此输入图像描述

在此输入图像描述

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 easiest way, 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 best way to do it is probably not to use the interface builder for this and make a subclass of UITableViewCell. 但是, 最好的方法是不要使用接口构建器,并创建UITableViewCell的子类。 For advanced customization, interface builders tend to only make things more complicated in my experience. 对于高级自定义,界面构建器往往只会让我的体验变得更复杂。 That's up to personal preference though. 这取决于个人偏好。

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

Yes this is possible : Make a image in gradient with 1 X Height pix. 是的,这是可能的:使用1 X高度像素制作渐变图像。 Set this to backgroundColor for cell. 将其设置为backgroundColor for cell。

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. 如果你填写得更好,那么搜索它。

answer by etayluz works 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). 在每次绘制时删除渐变图层,以便在需要重绘时不会继续绘制并添加新图层(例如,通过在旋转时调用.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) } } 

Based on etayluz answer I changed the code a little bit by taking the layerClass property of a UIView into 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]
    }

}

Create a simple view class with @IBInspectable properties. 使用@IBInspectable属性创建一个简单的视图类。

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

... ...

//
//  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 { $0.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
    }

}

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

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. 您可以在较旧的sdk和xCode版本中使用UISegmentedControl和一个段: http//chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/但是现在你不能在一个UISegmentedControl中创建少于两个段。 And even this way you couldn't change the default colors of the buttons without coding. 即使这样,您也无法在不编码的情况下更改按钮的默认颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 具有界面生成器视图的UIView背景渐变 - UIView Background Gradient With Interface Builder View 在Interface Builder中为渐变视图设置渐变背景颜色 - Setting up Gradient Background Colors in Interface Builder for a Gradient View 在Interface Builder中设置UIDatePicker背景颜色? - Set UIDatePicker background color in Interface Builder? xcode Interface Builder背景颜色首选项 - xcode Interface Builder background color preference 在“界面”构建器中更改UITableViewCell背景色 - Change UITableViewCell background color in Interface builder 在界面生成器中将颜色应用于uilabel会去背景吗? - Applying color to uilabel in interface builder goes to background? 有没有办法让自定义约束在界面构建器中工作? - Is there a way to make a custom constraint work in interface builder? 为什么UITableViewCell背景颜色不起作用(在界面生成器中设置)? - Why doesn't UITableViewCell background color work (set in interface builder)? 使用xcode 5界面构建器设置选项卡栏色调(背景)颜色 - using xcode 5 interface builder for setting tab bar tint (background) color @IBDesignable 视图不会在 Interface Builder 中绘制背景颜色 - @IBDesignable view doesn't draw background color inside Interface Builder
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM