如何在Swift中拆分UIView的背景颜色?

时间:2019-05-20 08:10:03

标签: swift xcode uibackgroundcolor

我想在应用程序屏幕中水平区分背景颜色。

我已经尝试过了,它走不通了。

var halfView1 = backgroundView.frame.width/2
backgroundView.backgroundColor.halfView1 = UIColor.black

backgroundView是故事板上的View对象的出口

例如,屏幕的一半是蓝色,屏幕的另一半是红色。

2 个答案:

答案 0 :(得分:3)

您应该创建一个自定义UIView类并覆盖draw rect方法

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(HorizontalView(frame: self.view.bounds))
    }
}
class HorizontalView: UIView {
    override func draw(_ rect: CGRect) {
        super.draw(rect)

        let topRect = CGRect(x: 0, y: 0, width: rect.size.width/2, height: rect.size.height)
        UIColor.red.set()
        guard let topContext = UIGraphicsGetCurrentContext() else { return }
        topContext.fill(topRect)

        let bottomRect = CGRect(x: rect.size.width/2, y: 0, width: rect.size.width/2, height: rect.size.height)
        UIColor.green.set()
        guard let bottomContext = UIGraphicsGetCurrentContext() else { return }
        bottomContext.fill(bottomRect)
    }
}

enter image description here

答案 1 :(得分:1)

如果您使用自定义UIView并覆盖了draw函数,则可能是一个Playground示例:

import UIKit
import PlaygroundSupport

class CustomView: UIView {

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

        backgroundColor = UIColor.green
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        let bottomRect = CGRect(
            origin: CGPoint(x: rect.origin.x, y: rect.height / 2),
            size: CGSize(width: rect.size.width, height: rect.size.height / 2)
        )
        UIColor.red.set()
        guard let context = UIGraphicsGetCurrentContext() else { return }
        context.fill(bottomRect)
    }
}

let view = CustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
PlaygroundPage.current.liveView = view