1

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

我试过这个,它无处可去。

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

backgroundView 是 Storyboard 上 View 对象的一个​​出口

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

4

2 回答 2

6

您应该创建一个自定义 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)
    }
}

在此处输入图像描述

于 2019-05-20T09:20:58.653 回答
1

如果您使用自定义 UIView 并覆盖绘图功能,这是可能的,这是一个 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
于 2019-05-20T08:38:47.213 回答