2017-04-11 8 views
1

UIImageView 인스턴스를 만들고 있습니다. UIImage를 클릭 할 수있게 만드는 데 문제가 있습니다. 또한 UIImage를 클릭하면 인터넷에있는 링크로 사용자를 보낼 수 있습니다. 이것을 어떻게 할 수 있습니까? 탭 제스쳐를 추가하려고했지만 행운이 없습니다. 주석 처리 된 코드로이를 볼 수 있습니다.UIImageView를 클릭하여 웹 사이트로 보내기

/파일 1 모델 파일/

import Foundation 

class Book : NSObject{ 
    var thumbnailImageName: String? 
    var title : String? 
    var subTitle : String? 
} 

/파일 2 셀 파일/

import UIKit 

class BookCell: BaseCell{ 
    var book: Book?{ 
     didSet{ 
      thumbnailImageView.image = UIImage(named: (book?.thumbnailImageName)!) 

      titleLabel.text = book?.title 

      subtitleTextView.text = book?.subTitle 
     } 
    } 

    var thumbnailImageView: UIImageView = { 
     let imageView = UIImageView() 

     // let tapGesture = UITapGestureRecognizer(target: imageView, action: #selector(BookCell.tapBlurButton(_:))) 

     imageView.image = UIImage(named: "") 
     imageView.userInteractionEnabled = true 
     imageView.tag = 0 
     imageView.contentMode = .ScaleAspectFit 
     imageView.clipsToBounds = true 
     // imageView.addTarget(self, action: #selector(self.tapBlurButton(_:)), forControlEvents: .TouchUpInside) 
     // imageView.addGestureRecognizer(tapGestureRecognizer) 
     return imageView 
    }() 

    let userProfileImageView: UIImageView = { 
     let imageView = UIImageView() 
     imageView.image = UIImage(named: "Gary Vee Profile Pic 1") 
     imageView.layer.cornerRadius = 22 
     imageView.layer.masksToBounds = true 
     return imageView 
    }() 

    let separatorView: UIView = { 
     let view = UIView() 
     view.backgroundColor = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1) 

     return view 
    }() 

    let titleLabel: UILabel = { 
     let label = UILabel() 

     label.translatesAutoresizingMaskIntoConstraints = false 
     label.text = "DailyVee 199" 
     label.userInteractionEnabled = false 
     return label 
    }() 

    let subtitleTextView: UITextView = { 
     let textView = UITextView() 
     textView.translatesAutoresizingMaskIntoConstraints = false 
     textView.text = "When a street hustler make 130 million" 
     textView.userInteractionEnabled = false 
     textView.textContainerInset = UIEdgeInsetsMake(0,-4,0,0) 
     textView.textColor = UIColor.darkGrayColor() 
     return textView 
    }() 

    let purchaseButton: UIButton = { 
     let button = UIButton(type: .System) // let preferred over var here 
     button.frame = CGRectMake(100, 100, 100, 50) 
     button.backgroundColor = UIColor.greenColor() 
     button.setTitle("Button", forState: UIControlState.Normal) 

     button.addTarget(button, action: #selector(Books.tapBlurButton(_:)), forControlEvents: .TouchUpInside) 

     return button 
    }() 

    override func setupViews(){ 
     addSubview(thumbnailImageView) 
     addSubview(separatorView) 
     addSubview(userProfileImageView) 
     addSubview(titleLabel) 
     addSubview(subtitleTextView) 
     addSubview(purchaseButton) 

     addContraintsWithFormat("H:|-16-[v0]-16-|", views: thumbnailImageView) 

     addContraintsWithFormat("H:|-16-[v0(44)]", views: userProfileImageView) 

     //Vertical constraints 
     addContraintsWithFormat("V:|-16-[v0]-8-[v1(44)]-16-[v2(1)]|", views: thumbnailImageView, userProfileImageView, separatorView) 

     addContraintsWithFormat("H:|[v0]|", views: separatorView) 

     //top constraint 
     addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Top, relatedBy: .Equal, toItem: thumbnailImageView, attribute:.Bottom, multiplier: 1, constant: 8)) 
     //left constraint 
     addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Left, relatedBy: .Equal, toItem: userProfileImageView, attribute:.Right, multiplier: 1, constant: 8)) 
     //right constraint 
     addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Right, relatedBy: .Equal, toItem: thumbnailImageView, attribute:.Right, multiplier: 1, constant: 0)) 
     //height constraint 
     addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Height, relatedBy: .Equal, toItem: self, attribute:.Height, multiplier: 0, constant: 20)) 

     //top constraint 
     addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .Top, relatedBy: .Equal, toItem: titleLabel, attribute:.Bottom, multiplier: 1, constant: 4)) 
     //left constraint 
     addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .Left, relatedBy: .Equal, toItem: userProfileImageView, attribute:.Right, multiplier: 1, constant: 8)) 
     //right constraint 
     addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .Right, relatedBy: .Equal, toItem: thumbnailImageView, attribute:.Right, multiplier: 1, constant: 0)) 
     //height constraint 
     addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .Height, relatedBy: .Equal, toItem: self, attribute:.Height, multiplier: 0, constant: 30)) 
    } 
} 

/파일 3 클래스 파일/

class Books : UICollectionViewController, UICollectionViewDelegateFlowLayout { 
    var books: [Book] = { 
     var askGaryVee = Book() 
     askGaryVee.thumbnailImageName = "askgaryvee_book" 
     askGaryVee.title = "#ASKGARYVEE: ONE ENTREPRENEUR'S TAKE ON LEADERSHIP, SOCIAL MEDIA, AND SELF-AWARENESS" 
     askGaryVee.subTitle = "by Gary Vaynerchuk" 

     var jabJabJabRightHook = Book() 
     jabJabJabRightHook.thumbnailImageName = "jab_jab_jab_right_hook_book" 
     jabJabJabRightHook.title = "JAB, JAB, JAB, RIGHT HOOK: HOW TO TELL YOUR STORY IN A NOISY SOCIAL WORLD" 
     jabJabJabRightHook.subTitle = "by Gary Vaynerchuk" 

     var theThankYouEconomy = Book() 
     theThankYouEconomy.thumbnailImageName = "the_thank_you_economy_book" 
     theThankYouEconomy.title = "The Thank You Economy" 
     theThankYouEconomy.subTitle = "by Gary Vaynerchuk" 

     var crushIt = Book() 
     crushIt.thumbnailImageName = "cursh_it_book" 
     crushIt.title = "CRUSH IT! WHY NOW IS THE TIME TO CASH IN ON YOUR PASSION" 
     crushIt.subTitle = "by Gary Vaynerchuk" 

     return[askGaryVee, jabJabJabRightHook, theThankYouEconomy, crushIt] 
    }() 

    func tapBlurButton(sender: AnyObject) { 
     print("Please Help!") 
    } 

    override func viewDidLoad() { 
     self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) 

     navigationItem.title = "Books" 

     collectionView!.backgroundColor = UIColor.whiteColor() 

     collectionView?.registerClass(BookCell.self, forCellWithReuseIdentifier:"cellId") 
    } 

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return books.count 
    } 

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 

     let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellId", forIndexPath: indexPath) as! BookCell 

     cell.book = books[indexPath.item] 

     return cell 
    } 

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 
     let height = (view.frame.width - 16 - 16) * 9/16 
     return CGSizeMake(view.frame.width, height + 16 + 68) 
    } 

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { 
     return 0 
    } 

} 
+0

탭 제스쳐의 대상은 '자체'여야합니다. 게다가'UIImageView'는'UIControl'이 아니기 때문에 컨트롤 이벤트를 추가 할 수 없습니다. – sooper

+0

내가 할 수있는 뭔가가 있습니까? 이 섹션에도 버튼이 있습니다. 단추로 사용자를 웹 사이트로 보낼 수 있습니까? –

답변

2

가장 쉬운 해결책은 UIImageView 상단에 투명 UIButton을 추가하고 UIButton의 프레임을 UIImageView과 동일하게 설정하는 것입니다. 그런 다음 UIButtonIBAction을 사용하여 사용자를 링크로 보낼 수 있습니다.

var tumbnailButton: UIButton = { 
    let button = UIButton(frame: thumbnailImageView.frame) 
    button.addTarget(self, action: #selector(tapBlurButton(_:)), for: .touchUpInside) 
    button.clipsToBounds = true 
    return button 
}() 

편집 :이 계산 된 특성 때문에 은 위의 코드는 오류가 발생 할 수 있습니다.

var tumbnailButton: UIButton { 

var tumbnailButton: UIButton = { 

를 교체 시도하고 끝 부분에 괄호를 제거합니다. 그래도 문제가 해결되지 않으면

, 그리고 UIView의

extension UIImageView { 
     public func addTapGesture(tapNumber: Int = 1, action: ((UITapGestureRecognizer) ->())?) { 
      let tap = BlockTap(tapCount: tapNumber, fingerCount: 1, action: action) 
      addGestureRecognizer(tap) 
      isUserInteractionEnabled = true 
     } 
    } 

당신이 할 수있는
open class BlockTap: UITapGestureRecognizer { 
    fileprivate var tapAction: ((UITapGestureRecognizer) -> Void)? 

public override init(target: Any?, action: Selector?) { 
    super.init(target: target, action: action) 
} 

public convenience init (
    tapCount: Int = 1, 
    fingerCount: Int = 1, 
    action: ((UITapGestureRecognizer) -> Void)?) { 
     self.init() 
     self.numberOfTapsRequired = tapCount 

     #if os(iOS) 
     self.numberOfTouchesRequired = fingerCount 
     #endif 

     self.tapAction = action 
     self.addTarget(self, action: #selector(BlockTap.didTap(_:))) 
} 

open func didTap (_ tap: UITapGestureRecognizer) { 
    tapAction? (tap) 
} 
} 

는 다음의 UIImageView의 확장 또는을 UITapGestureRecognizer

를 상속이 클래스를 확인

var tumbnailButton: UIButton { 
    get{ 
     let button = UIButton(frame: thumbnailImageView.frame) 
     button.addTarget(self, action: #selector(tapBlurButton(_:)), for: .touchUpInside) 
     button.clipsToBounds = true 
     return button 
    } 
} 
+0

Brilliant! 고맙습니다. –

+0

TapGestureRecognizer를 이미지 위에 곧바로 추가 할 수 있으며 잘 작동합니다! – iDeveloper

+0

위의 코드를 사용하면 thumbnailImageView와 관련된 오류가 발생합니다."인스턴스 멤버 thumbnailImageView를 Bookcell 유형에 사용할 수 없습니다."라는 메시지가 나타납니다. –

0

시도 이것을

으로 사용하십시오. 코드에서
imageView?.addTapGesture(action: {[unowned self] (_) in 
       //Do whatever on click of image 
}) 

당신은 당신이 4.0로 변경됩니다 이미지의 이미지 뷰 CornerRadius를의 클릭에

let userProfileImageView: UIImageView = { 
    let imageView = UIImageView() 
     imageView.image = UIImage(named: "Gary Vee Profile Pic 1") 
     imageView.layer.cornerRadius = 22 
     imageView.layer.masksToBounds = true 
     imageView?.addTapGesture(action: {[unowned self] (_) in 
      //Code you want to execute on click of Imageview 
      imageView?.cornerRadius = 4.0 
      imageView?.clipsToBounds = true 
     }) 
      return imageView 
     }() 

같은 코드에서 어떤 이미지 뷰에 addTapGesture을 사용할 수 있습니다

로 사용할 수 있습니다.

+0

어디에서 imageview? addtapgesture를 사용할 수 있습니까? 어디 코드에서? –

+0

답변을 편집했습니다. viewDidLoad의 imageview에 addTapGesture를 사용할 수 있습니다. 이미지가 도청 될 때마다 addTapGesture 블록이 호출됩니다. 호프가 도움이 될 때마다 –

+0

"imageView? .addTapGesture (action : {[unowned self] (_) in"을 입력 할 때마다 오류가 발생합니다. 위의 코드를 보면 3 개의 다른 파일이 있음을 알 수 있습니다. 클래스 및 UICollectionViewController 셀을 수동으로 만드는 다른 파일을 재정의하는 클래스. viewDidLoad() 내에서 코드를 퍼팅 또한 imageView 해당 파일에서 선언 된 때문에 작동하지 않습니다. 해당 셀 파일에 선언 된. UICollectionViewController 파일 –

관련 문제