Итак, я делаю простую игру на основе шестиугольников. Вот как это выглядит:Создание UIButton с формой CAShapeLayer
Я сумел нарисовать шестиугольники именно так, как я хочу их CAShapeLayer
с, но я хотел бы, чтобы сделать их интерактивными. Короче говоря, я хотел бы как-то отбросить их в UIButtons
, чтобы я мог отслеживать, какой из них выбран через touchUpInside. Другим способом, который я могу придумать, является отслеживание касаний и проверка, были ли они в форме с тегом, но это кажется сложным. Ниже мой код:
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
let radius : CGFloat = screenWidth/6
var c = 0
var counter = 0
for j in 1...6 {
for i in 1...3 {
for x in 1...2 {
var center = CGPoint(x: CGFloat((i-1)*2)*radius+CGFloat(i-1)*radius, y: CGFloat((j-1)*2)*radius)
if (x==2) {
center.x = center.x+1.5*radius
center.y = center.y+radius
}
let shape = CAShapeLayer()
view.layer.addSublayer(shape)
shape.opacity = 0.5
shape.lineWidth = 2
shape.lineJoin = kCALineJoinMiter
shape.strokeColor = UIColor(hue: 0.786, saturation: 0.79, brightness: 0.53, alpha: 1.0).CGColor
shape.fillColor = UIColor(hue: 0.786, saturation: 0.15, brightness: 0.89, alpha: 1.0).CGColor
let path = UIBezierPath()
path.moveToPoint(CGPointMake(center.x-radius, center.y))
path.addLineToPoint(CGPointMake(center.x-radius/2, center.y-radius))
path.addLineToPoint(CGPointMake(center.x+radius/2, center.y-radius))
path.addLineToPoint(CGPointMake(center.x+radius, center.y))
path.addLineToPoint(CGPointMake(center.x+radius, center.y))
path.addLineToPoint(CGPointMake(center.x+radius/2, center.y+radius))
path.addLineToPoint(CGPointMake(center.x-radius/2, center.y+radius))
path.closePath()
shape.path = path.CGPath
}
}
}
Эй, спасибо за ответ! В этом есть смысл. Можно ли, например, установить UIButton с помощью слоя формы? Как я могу сделать шестиугольник UIButton? – Antoine
Добавлен пример кода. – matt