Подвид UIView находится в неожиданном положении (Swift 4) - PullRequest
0 голосов
/ 03 июня 2018

Я пытаюсь добавить 4 подвида UIView в UIImageView.Эти подпредставления должны действовать как узлы, где пользователь может коснуться их и подключиться к другим узлам.Например, они должны выглядеть вот так .Вместо этого они выглядят вот так .

Мой код для расчета позиций узлов выглядит следующим образом:

func initializeConnectionNodes() {
        let imageCenter = self.imageView.center
        let xOffset = self.imageView.bounds.width/2 //distance from origin x-wise
        let yOffset = self.imageView.bounds.height/2 //distance from origin y-wise
        self.leftConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: imageCenter.x - xOffset, y: imageCenter.y))
        self.rightConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: imageCenter.x + xOffset, y: imageCenter.y))
        self.topConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: imageCenter.x, y: imageCenter.y + yOffset))
        self.bottomConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: imageCenter.x, y: imageCenter.y - yOffset))

        self.imageView.addSubview(self.leftConnectionNode!)
        self.imageView.addSubview(self.rightConnectionNode!)
        self.imageView.addSubview(self.topConnectionNode!)
        self.imageView.addSubview(self.bottomConnectionNode!)
}

Мой код для инициализации класса UIView имеет видследует:

class ConnectionNodeView: UIView {

var connectionPoint: CGPoint
fileprivate var circleLayer: CAShapeLayer?

init(connectionPoint: CGPoint) {
    self.connectionPoint = connectionPoint
    super.init(frame: CGRect(x: connectionPoint.x, y: connectionPoint.y, width: 0, height: 0))

    let circlePath = UIBezierPath(arcCenter: connectionPoint, radius: CGFloat(8), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)
    self.circleLayer = CAShapeLayer()
    self.circleLayer?.path = circlePath.cgPath
    self.circleLayer?.fillColor = UIColor.yellow.cgColor
    self.circleLayer?.strokeColor = UIColor.yellow.cgColor
    self.circleLayer?.lineWidth = 3.0
    self.layer.addSublayer(circleLayer!)
}

Интересно отметить, что если я просто добавлю CAShapeLayer в качестве подслоя к моему UIImageView, то это выглядит так, как и должно быть.Однако мне нужно реализовать его как UIView, чтобы я мог легко использовать распознаватели жестов.Я нашел грязный способ исправить это, разделив координаты на 100 в инициализаторе следующим образом:

super.init(frame: CGRect(x: connectionPoint.x/100, y: connectionPoint.y/100, width: 0, height: 0))

Однако я бы предпочел сделать это правильно.Что мне здесь не хватает?Спасибо за вашу помощь.

1 Ответ

0 голосов
/ 03 июня 2018

Вы добавляете виды к виду изображения, но точка imageCenter задается в соответствии с суперпредставлением вида изображения.

Замените начало initializeConnectionNodes функция со следующим:

let xCenter = imageView.bounds.width / 2
let yCenter = imageView.bounds.height / 2

leftConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: 0, y: yCenter))
rightConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: imageView.bounds.width, y: yCenter))
topConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: xCenter, y: 0))
bottomConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: xCenter, y: imageView.bounds.height))

Кроме того, вы должны заменить центр дуги circlePath в вашем подклассе ConnectionNodeView на CGPoint.zero, так как он работает с системой координат самого представления узла:

let circlePath = UIBezierPath(arcCenter: .zero, radius: 8, startAngle: 0, endAngle:CGFloat(Double.pi * 2), clockwise: true)
...