Я знаю, что подобные вопросы были размещены на StackOverflow, но, несмотря на то, что я следовал руководствам, я не смог справиться со своим вопросом.
У меня есть красный прямоугольник, который я хотел бы разместить в центре представления, но он заканчивается в начале координат, например:
Следуя некоторым руководствам, я пришел к следующему коду, но прямоугольник не отображается вообще.
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
import CoreGraphics
class MyViewController : UIViewController {
var currentDrawType = 0
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// Buton logic follows
let button = UIButton(type: .system)
button.frame = CGRect(x:150, y:500, width:80, height:25)
button.backgroundColor = .white
button.setTitle("Test Button", for: .normal)
button.titleLabel?.textColor = .systemBlue
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
super.view.addSubview(button)
// Other
drawRectangle()
}
@objc func buttonAction(sender: UIButton!) {
currentDrawType += 1
if currentDrawType > 5 {
currentDrawType = 0
}
switch currentDrawType {
case 0:
drawRectangle()
default:
break
}
print(currentDrawType)
}
func drawRectangle() {
var imageView = UIImageView()
imageView.frame.origin = super.view.bounds.origin
imageView.frame.size = CGSize(width:200, height:200)
imageView.center = super.view.convert(super.view.center, from: imageView)
super.view.addSubview(imageView)
UIGraphicsBeginImageContextWithOptions(imageView.frame.size, false, 0)
let context = UIGraphicsGetCurrentContext()
let rectangle = imageView.frame
context!.setFillColor(UIColor.red.cgColor)
context!.setStrokeColor(UIColor.black.cgColor)
context!.setLineWidth(10)
context!.addRect(rectangle)
// Draw it now
context!.drawPath(using: CGPathDrawingMode.fillStroke)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageView.image = img
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
Кроме того, я хотел бы отрегулировать размер основного вид, но я не совсем уверен, как это сделать. Когда у меня была немного другая реализация, я изменил размер, но физическое окно просмотра в Xcode, где отображался результат, не изменилось, и, следовательно, элементы не были видны.
Мне нужна помощь и / или руководство по этому поводу.