質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

1712閲覧

アニメーション中にボタンをタップしたい

aaaaaachannel

総合スコア37

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2018/02/09 02:50

何度も同じ質問をしてすいません。質問の仕方も下手くそですいません。
アニメーションさせたボタンがアニメーション中にボタンをタップしたいのですが、できません。

swift

1 // viewをタップされた時の処理 2 @objc func viewTap(sender: UITapGestureRecognizer){ 3 print("GAMEOVER") 4 5 } 6

最初、UIRecognizerを使おうと思い、このようにしたところviewはタップするとGAMEOVERと表示されます。しかしどうやってボタンと識別すればいいのかがわかりません。

次に、presentationlayerを使おうと考えました。以下のサイトを参考にしましたが、これも viewの例でuibuttonへの適用がわかりませんでした。また、ボタンではない、viewはpresentationlayerがなくても反応しているのでちょっと違うのかなと思いました。

(https://ja.stackoverflow.com/questions/31506/アニメーション中のビューをタップしてイベント処理?rq=1)

やりたいことをまとめると、
1アニメーションで流れる画面でタップした場所がボタンかボタン以外の画面かを判定する
2ボタンの場合、正しくボタンを押したのかボタンのタグで判定する
ということです。

以下、コードの全文を貼ります。

swift

1 2 3import UIKit 4import AVFoundation 5 6let urls: [String] = ["1:2","3:4","5:6:7", "8","9","10","11","12","13:14:15","1:2","3:4","5:6:7", "8","9","10","11","12","13:14:15"] 7 8 9 10class ViewController: UIViewController{ 11 12 13 let largeImageView = UIImageView() 14 var imageHeight:CGFloat! 15 16 //makenote 17 var note:UIButton! 18 19 var duration:Double! 20 var durations:[Double] = [] 21 22 var heights:[CGFloat] = [] 23 var sum:CGFloat = 0 24 25 var number:CGFloat! = 0 26 var differenceNumber:CGFloat! = 0 27 var intNumber:Int! = 0 28 29 var needHeights:[Int] = [] 30 var needsum:Int! 31 32 var withduration:CGFloat! 33 var notes:[UIButton] = [] 34 var tags:[Int] = [] 35 36 //music 37 var audioPlayer :AVAudioPlayer! = nil 38 39 40 41 override func viewDidLoad() { 42 43 super.viewDidLoad() 44 // Do any additional setup after loading the view, typically from a nib 45 view.isUserInteractionEnabled = true 46 largeImageView.isUserInteractionEnabled = true 47 makeSound() 48 setBackGround() 49 makeLine() 50 51 52 53 54 55 56 57 } 58 59 override func viewDidAppear(_ animated: Bool) { 60 super.viewDidAppear(animated) 61 Timer.scheduledTimer(withTimeInterval: 0.016, repeats: true) { (timer) in 62 self.largeImageView.center.y += 1.0 63 if self.largeImageView.center.y >= self.view.bounds.size.width { 64 timer.invalidate() 65 } 66 } 67 } 68 69 70 override func didReceiveMemoryWarning() { 71 super.didReceiveMemoryWarning() 72 // Dispose of any resources that can be recreated. 73 } 74 75 @objc func tap(_ gestureRecognizer: UIGestureRecognizer) { 76 let point = gestureRecognizer.location(in: view) 77 if let presentation = largeImageView.layer.presentation(), 78 let _ = presentation.hitTest(point) { 79 print("G") 80 note?.sendActions(for: .touchUpInside) 81 82 83 84 } 85 } 86 87 88// // viewをタップされた時の処理 89// @objc func viewTap(sender: UITapGestureRecognizer){ 90// print("GAMEOVER") 91// 92// 93// } 94// 95 96 func setBackGround(){ 97 //背景 98 99 //neednumber 100 for url in urls { 101 let soundFilePath:NSString = Bundle.main.path(forResource:url, ofType: "mp3")! as NSString 102 let sound :URL = URL(fileURLWithPath: soundFilePath as String) 103 do { 104 let audioFile: AVAudioFile = try AVAudioFile(forReading: sound) 105 let sampleRate = audioFile.fileFormat.sampleRate 106 duration = Double(audioFile.length) / sampleRate 107 //all fine with jsonData here 108 } catch { 109 //handle error 110 print(error) 111 } 112 113 if 0 < duration && duration < 1.5{ 114 //1 115 let one = 50 116 needHeights.append(one) 117 118 } 119 else if 1.5 < duration && duration < 2.5{ 120 //2 121 let two = 100 122 needHeights.append(two) 123 124 125 } 126 else if 2.5 < duration && duration < 3.5{ 127 //3 128 let three = 150 129 needHeights.append(three) 130 } 131 needsum = needHeights.reduce(0){ $0 + $1 } 132 print("needsum") 133 print(needsum) 134 135 } 136 137 number = CGFloat(needsum)/self.view.frame.height 138 print(number) 139 140 141 142 //画像 143 var imageViewArray:Array<UIImageView> = [] 144 let img = UIImage(named: "background") 145 let imageView = UIImageView(image:img) 146 imageHeight = imageView.bounds.height*number 147 148 largeImageView.frame = CGRect(x: 0, y:-imageHeight,width:self.view.frame.width,height:imageHeight) 149 150 151 print(largeImageView.frame) 152 print(imageView.frame.height) 153 print(imageView.bounds.height) 154 155 156 for i in 0..<Int(number){ 157 let imageView = UIImageView(image:img) 158 imageView.frame = CGRect(x: 0, y: CGFloat(i) * imageView.bounds.height,width:self.view.frame.width,height:imageView.bounds.height) 159 self.view.sendSubview(toBack: imageView) 160 largeImageView.addSubview(imageView) 161 imageViewArray.append(imageView) 162 print(imageView.frame) 163 print(CGFloat(i) * imageView.bounds.height) 164 165 } 166 167 view.addSubview(largeImageView) 168 169 //makenote 170 171 for (index,url) in urls.enumerated() { 172 let soundFilePath:NSString = Bundle.main.path(forResource:url, ofType: "mp3")! as NSString 173 let sound :URL = URL(fileURLWithPath: soundFilePath as String) 174 do { 175 let audioFile: AVAudioFile = try AVAudioFile(forReading: sound) 176 let sampleRate = audioFile.fileFormat.sampleRate 177 duration = Double(audioFile.length) / sampleRate 178 durations.append(duration) 179 //all fine with jsonData here 180 } catch { 181 //handle error 182 print(error) 183 } 184 185 186 let width = self.view.frame.width 187 188 intNumber = Int(number) 189 differenceNumber = number-CGFloat(intNumber) 190 191 let note = UIButton() 192 193 if 0 < duration && duration < 1.5{ 194 //1 195 print(sum) 196 197 let randNum = arc4random_uniform(4) 198 note.frame = CGRect(x:CGFloat(randNum) * width/4.0,y:0+imageHeight-imageView.frame.height*differenceNumber-sum,width:width/4.0,height:50) 199 heights.append(note.frame.height) 200 sum = heights.reduce(0){ $0 + $1 } 201 note.frame = CGRect(x:CGFloat(randNum) * width/4.0,y:0+imageHeight-imageView.frame.height*differenceNumber-sum,width:width/4.0,height:50) 202 203 print(sum) 204 } 205 else if 1.5 < duration && duration < 2.5{ 206 //2 207 print(sum) 208 209 let randNum = arc4random_uniform(4) 210 note.frame = CGRect(x:CGFloat(randNum) * width/4.0,y:0+imageHeight-imageView.frame.height*differenceNumber-sum,width:width/4.0,height:100) 211 heights.append(note.frame.height) 212 sum = heights.reduce(0){ $0 + $1 } 213 note.frame = CGRect(x:CGFloat(randNum) * width/4.0,y:0+imageHeight-imageView.frame.height*differenceNumber-sum,width:width/4.0,height:100) 214 215 print(sum) 216 217 } 218 else if 2.5 < duration && duration < 3.5{ 219 //3 220 221 print(sum) 222 223 let randNum = arc4random_uniform(4) 224 note.frame = CGRect(x:CGFloat(randNum) * width/4.0,y:0+imageHeight-imageView.frame.height*differenceNumber-sum,width:width/4.0,height:150) 225 heights.append(note.frame.height) 226 sum = heights.reduce(0){ $0 + $1 } 227 note.frame = CGRect(x:CGFloat(randNum) * width/4.0,y:0+imageHeight-imageView.frame.height*differenceNumber-sum,width:width/4.0,height:150) 228 229 print(sum) 230 231 } 232 233 234 note.backgroundColor = UIColor.black 235 note.layer.borderColor = UIColor.white.cgColor 236 note.layer.borderWidth = 1.0 237 note.tag = index 238 239 tags.append(note.tag) 240 notes.append(note) 241 242 note.addTarget(self, action: #selector(ViewController.buttonTapped(sender:)), for: .touchUpInside) 243 largeImageView.addSubview(note) 244 245 246 247 } 248 249 print(tags) 250 251 252 //seconds 253 let notePerSecond = 1 254 let noteNumber = sum/50.0 255 withduration = CGFloat(notePerSecond) * noteNumber 256 257 // アニメーション処理 258 UIView.animate(withDuration: TimeInterval(withduration), delay: 0, options: [.transitionCrossDissolve,.allowUserInteraction], animations: { 259 self.largeImageView.frame = CGRect(x: 0, y: 0,width:self.view.frame.width,height:self.imageHeight) 260 261 }) { _ in 262 263 } 264 265 266 267 268 //layerpresentation 269 let _selector = #selector(tap(_:)) 270 let gesture = UITapGestureRecognizer(target: self, action: _selector) 271 view.addGestureRecognizer(gesture) 272 273} 274 275 func makeLine(){ 276 //中略(線を引く処理) 277 278 } 279 280 281 282 func makeSound(){ 283 284 let soundFilePath:NSString = Bundle.main.path(forResource: "Pathetique", ofType: "mp3")! as NSString 285 let sound :NSURL = NSURL(fileURLWithPath: soundFilePath as String) 286 do{ 287 audioPlayer = try AVAudioPlayer(contentsOf:sound as URL, fileTypeHint:nil) 288 }catch{ 289 print("error") 290 } 291 audioPlayer.prepareToPlay() 292 293 } 294 @objc func buttonTapped(sender:Any){ 295 var tag2:Int! 296 let tappedNote = sender as AnyObject 297 let tag = tappedNote.tag 298 UIApplication.shared.beginIgnoringInteractionEvents() 299 300 if tag == 0{ 301 audioPlayer.currentTime = 0.0 302 self.audioPlayer.play() 303 304 305 DispatchQueue.main.asyncAfter(deadline: .now() + durations[0]) { 306 self.audioPlayer.pause() 307 UserDefaults.standard.set(tag, forKey: "integerKeyName") 308 } 309 310 }else{ 311 tag2 = UserDefaults.standard.integer(forKey: "integerKeyName") 312 if tag == tag2 + 1{ 313 314 let rangeArray = durations.prefix(tag!) 315 let minutes = rangeArray.reduce(0) { $0 + $1 } 316 audioPlayer.currentTime = minutes 317 self.audioPlayer.play() 318 UserDefaults.standard.set(tag, forKey: "integerKeyName") 319 320 321 let pauseTime = durations[tag!] 322 DispatchQueue.main.asyncAfter(deadline: .now() + pauseTime) { 323 self.audioPlayer.pause() 324 325 print(pauseTime) 326 327 } 328 329 }else{ 330 print("ミス!") 331 } 332 } 333 334 } 335 336 337 338 339 340 341} 342 343 344 345 346

めんどくさくてすいません。よろしくお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

「UIViewなら出来る」のでしたら、UIButtonをやめてUIViewやUILabelなどにしてはどうでしょうか?
(UIButtonを使う必要は無さそうなので)

投稿2018/02/09 02:59

編集2018/02/09 03:02
fuzzball

総合スコア16731

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問