I have looked and tried every solution I could find online as to why my animations is not properly firing. DISCLOSURE: they work fine when put in viewDidAppear(). This question has been asked countless times but none of the solutions work. The results of the animations appear but not with the delay specified, they are instant. What I would like is to fade in a my requestRideButton in and out using either isHidden with UIView.transition or alpha with UIView.animate.
I would also like to move the button while it is fading. I have tried every combination of self.view.layoutIfNeeded() both in and out the animate closure with the constraint in and out. I have also tried it with self.view.superview?.layoutIfNeeded()
class RideRequestViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var rideRequestBottomButtonConstraint: NSLayoutConstraint!
#IBOutlet weak var rideRequestButtonTopConstraint: NSLayoutConstraint!
// Views
#IBOutlet var mapView: MKMapView!
#IBOutlet var rideDetailsView: UIView!
#IBOutlet var requestRideButton: UIButton!
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Layout map view to fill screen
mapView.frame = view.bounds
// Apply corner radius and shadow styling to floating views
let cornerRadius: CGFloat = 5.0
inputContainerView.layoutCornerRadiusAndShadow(cornerRadius: cornerRadius)
originButton.layoutCornerRadiusMask(corners: [.topLeft, .topRight], cornerRadius: cornerRadius)
paymentButton.layoutCornerRadiusMask(corners: .bottomLeft, cornerRadius: cornerRadius)
priceButton.layoutCornerRadiusMask(corners: .bottomRight, cornerRadius: cornerRadius)
rideDetailsView.layoutCornerRadiusAndShadow(cornerRadius: cornerRadius)
pilotView.layoutCornerRadiusMask(corners: [.topLeft, .bottomLeft], cornerRadius: cornerRadius)
vehicleView.layoutCornerRadiusMask(corners: [.topRight, .bottomRight], cornerRadius: cornerRadius)
requestRideButton.layoutCornerRadiusAndShadow(cornerRadius: cornerRadius)
}
override func viewDidLoad() {
ref = Database.database().reference()
}
func animate() {
self.rideRequestButtonTopConstraint.constant = -44
UIView.animate(withDuration: 1) {
self.view.layoutIfNeeded()
}
}
#IBAction
private func handleRequestRideButtonTapped() {
switch rideRequestState {
case .none:
// Update to requesting state
rideRequestState = .requesting
// Perform payment request
paymentContext.requestPayment()
case .requesting:
// Do nothing
// Show button
break
case .active:
// Complete the ride
completeActiveRide()
}
}
private func reloadRequestRideButton() {
guard originPlacemark != nil && destinationPlacemark != nil && paymentContext.selectedPaymentMethod != nil else {
// Show disabled state
requestRideButton.backgroundColor = .riderGrayColor
requestRideButton.setTitle("CONFIRM DELIVERY", for: .normal)
requestRideButton.setTitleColor(.black, for: .normal)
requestRideButton.setImage(nil, for: .normal)
requestRideButton.isEnabled = false
return
}
animate() // <--- view just disappears instantly instead
switch rideRequestState {
case .none:
// Show enabled state
requestRideButton.backgroundColor = .riderYellowColor
requestRideButton.setTitle("CONFIRM DELIVERY", for: .normal)
requestRideButton.setTitleColor(.black, for: .normal)
requestRideButton.setImage(nil, for: .normal)
requestRideButton.isEnabled = true
case .requesting:
// Show loading state
requestRideButton.backgroundColor = .riderYellowColor
requestRideButton.setTitle("...", for: .normal)
requestRideButton.setTitleColor(.white, for: .normal)
requestRideButton.setImage(nil, for: .normal)
requestRideButton.isEnabled = false
case .active:
// Show completion state
requestRideButton.backgroundColor = .white
requestRideButton.setTitle("Complete Ride", for: .normal)
requestRideButton.setTitleColor(.riderDarkBlueColor, for: .normal)
requestRideButton.setImage(nil, for: .normal)
requestRideButton.isEnabled = true
}
}
Changes to views to be animated should be inside the animate block.
func animate() {
UIView.animate(withDuration: 1) {
self.rideRequestButtonTopConstraint.constant = -44
self.view.layoutIfNeeded()
}
}
Changing the constraint in the line above will just update a value and move the view. It won't animate it
UPDATE
So based on looking at another answer and some additional research, The author of UIKit suggests that we update constraints and call layoutIfNeeded inside the animation block like above.
Here is the playground I used to test it
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
let movableView = UIView()
var topConstraint: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
view.addSubview(button)
button.setTitle("Animate", for: .normal)
button.addTarget(self, action: #selector(animate), for: .touchUpInside)
view.addSubview(movableView)
movableView.backgroundColor = .red
movableView.translatesAutoresizingMaskIntoConstraints = false
topConstraint = NSLayoutConstraint(item: movableView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 100)
topConstraint?.isActive = true
NSLayoutConstraint(item: movableView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: movableView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100).isActive = true
NSLayoutConstraint(item: movableView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100).isActive = true
}
#objc func animate() {
UIView.animate(withDuration: 4.0, animations: {
self.topConstraint?.constant = -100
self.view.layoutIfNeeded()
})
}
}
let vc = ViewController()
PlaygroundPage.current.liveView = vc.view
Related
I'm trying to add views(or buttons) to UIStackView dynamically.
At first, the UIStackView has no arranged views (vertically), and
after getting from some http response, several views(buttons) are added to UIStackView.
UIStackView is also autolayout to hold a specific area.
I've tried to find dynamic adding example, but failed.
Anyone can show me the examples of adding view onto UIStackView dynamically?
It may help you. Please follow this points:
Add UIScrollView to your UIViewController in storyboard or XIB.
Initiate an NSMutableArray name it arrViews gets server response and adds view in the array.
Initialise UIStackViewpass arrView array in the init method.
After that UIStackView will be added subview of UIScrollView.
Add constraint programmatically to UIStackView. That's it.
if let response = self.serverResponse {
if let body = response.responseBody {
if let view = body.views {
arrViews = createSubViews(view)
}
}
}
let stackView = UIStackView(arrangedSubviews: arrViews)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = 16
stackView.distribution = .fill
self.scrollView.addSubview(stackView)
//constraints
let leading = NSLayoutConstraint(item: stackView, attribute: .leading, relatedBy: .equal, toItem: self.scrollView, attribute: .leading, multiplier: 1.0, constant: 0)
self.scrollView.addConstraint(leading)
let trailing = NSLayoutConstraint(item: stackView, attribute: .trailing, relatedBy: .equal, toItem: self.scrollView, attribute: .trailing, multiplier: 1.0, constant: 0)
self.scrollView.addConstraint(trailing)
let top = NSLayoutConstraint(item: stackView, attribute: .top, relatedBy: .equal, toItem: self.scrollView, attribute: .top, multiplier: 1.0, constant: 0)
self.scrollView.addConstraint(top)
let bottom = NSLayoutConstraint(item: stackView, attribute: .bottom, relatedBy: .equal, toItem: self.scrollView, attribute: .bottom, multiplier: 1.0, constant: 0)
self.scrollView.addConstraint(bottom)
let equalWidth = NSLayoutConstraint(item: stackView, attribute: .width, relatedBy: .equal, toItem: self.scrollView, attribute: .width, multiplier: 1.0, constant: 0)
self.scrollView.addConstraint(equalWidth)
leading.isActive = true
trailing.isActive = true
top.isActive = true
bottom.isActive = true
equalWidth.isActive = true
Hope it will help you. Happy coding :)
I use this code in one of my projects:
let baseFrame = CGRect(origin: .zero, size: CGSize(width: requiredWidth, height: partitionHeight))
for instrument in instruments {
let partitionView = PartitionOnDemand(instrument: instrument, mode: playbackMode, frame: baseFrame, referenceView: partitionsAnimator)
partitionsStackView.addArrangedSubview(partitionView)
let tab = InstrumentInfoTabContainer.instantiate(with: instrument) {
self.focus(on: instrument)
}
tabsStackView.addArrangedSubview(tab)
}
While trying with answers, I happend to find how to work it.
class ViewController: UIViewController {
#IBOutlet weak var stack: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func onBtn_Create(_ sender: Any) {
createButton("new button ...")
}
#IBAction func onBtn_Delete(_ sender: Any) {
if let v = stack.arrangedSubviews.last {
stack.removeArrangedSubview(v)
v.removeFromSuperview()
}
}
func createButton(_ title: String) {
let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
button.backgroundColor = UIColor.blue
button.setTitle(title, for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
stack.addArrangedSubview(button)
}
#objc func buttonAction(sender: UIButton!) {
print("Button tapped")
}
}
And, I anchored to UIStackView, Trailing=0, Leading=0, Top=0, Bottom=8 to TextView.Top
The subviews inside it are intact without any constraints.
Thank you.
I want put Ad banner in my app.
I don't have the storyboard, I 've 4 ViewCOntroller, in the main I've this, can someone help me please?
In AppDelegate: GADMobileAds.configure(withApplicationID: "...")
import UIKit
import Firebase
import GoogleMobileAds
class ViewController: UIViewController {
var window: UIWindow?
override func viewDidLoad(){
super.viewDidLoad()
self.title="Andrea Damante Quiz"
self.view.backgroundColor=UIColor(patternImage: UIImage(named: "andrea15.jpeg")!)
let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "andrea15.jpeg")
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)
setupViews()
}
#objc func btnGetStartedAction() {
let v=QuizVC()
self.navigationController?.pushViewController(v, animated: true)
}
func setupViews() {
self.view.addSubview(lblTitle)
lblTitle.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 150).isActive=true
lblTitle.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive=true
lblTitle.widthAnchor.constraint(equalToConstant: 250).isActive=true
lblTitle.heightAnchor.constraint(equalToConstant: 80).isActive=true
self.view.addSubview(btnGetStarted)
btnGetStarted.heightAnchor.constraint(equalToConstant: 50).isActive=true
btnGetStarted.widthAnchor.constraint(equalToConstant: 150).isActive=true
btnGetStarted.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive=true
btnGetStarted.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: 0).isActive=true
}
let lblTitle: UILabel = {
let lbl=UILabel()
lbl.text="Quiz"
lbl.textColor=UIColor.darkGray
lbl.textAlignment = .center
lbl.font = UIFont.systemFont(ofSize: 46)
lbl.numberOfLines=2
lbl.translatesAutoresizingMaskIntoConstraints=false
return lbl
}()
let btnGetStarted: UIButton = {
let btn=UIButton()
btn.setTitle("Via!", for: .normal)
btn.setTitleColor(UIColor.white, for: .normal)
btn.backgroundColor=UIColor.orange
btn.layer.cornerRadius=5
btn.layer.masksToBounds=true
btn.translatesAutoresizingMaskIntoConstraints=false
btn.addTarget(self, action: #selector(btnGetStartedAction), for: .touchUpInside)
return btn
}()
}
You need to declare and set up a GADBannerView and add it to your view controller. You won't need a UIWindow. Use this code:
import GoogleMobileAds
import UIKit
class ViewController: UIViewController {
var bannerView: GADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
// In this case, we instantiate the banner with desired ad size.
bannerView = GADBannerView(adSize: kGADAdSizeBanner)
addBannerViewToView(bannerView)
}
func addBannerViewToView(_ bannerView: GADBannerView) {
bannerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(bannerView)
view.addConstraints(
[NSLayoutConstraint(item: bannerView,
attribute: .bottom,
relatedBy: .equal,
toItem: bottomLayoutGuide,
attribute: .top,
multiplier: 1,
constant: 0),
NSLayoutConstraint(item: bannerView,
attribute: .centerX,
relatedBy: .equal,
toItem: view,
attribute: .centerX,
multiplier: 1,
constant: 0)
])
}
}
which was taken from here: https://developers.google.com/admob/ios/banner.
Also make sure to set the ad unit ID and the delegate:
override func viewDidLoad() {
super.viewDidLoad()
...
bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
bannerView.rootViewController = self
bannerView.load(GADRequest())
}
But again, you'll everything you need in the official guide.
I am making UIImageView instances. I am having trouble making the UIImage clickable. I also would like the UIImage when clicked to send the user to a link on the Internet. How can I accomplish this? I have tried adding tap gestures and such but am having no luck. You can see this with the code that is commented out.
/File 1 Model File/
import Foundation
class Book : NSObject{
var thumbnailImageName: String?
var title : String?
var subTitle : String?
}
/File 2 Cell File/
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))
}
}
/File 3 Class File/
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
}
}
The easiest solution is to add a clear UIButton on top of your UIImageView and set the frame of your UIButton to be the same as your UIImageView. Then you can use the UIButton's IBAction to send the user to the link.
var tumbnailButton: UIButton = {
let button = UIButton(frame: thumbnailImageView.frame)
button.addTarget(self, action: #selector(tapBlurButton(_:)), for: .touchUpInside)
button.clipsToBounds = true
return button
}()
EDIT:
The above code might throw an error since it is a computed property. Try replacing
var tumbnailButton: UIButton = {
with
var tumbnailButton: UIButton {
and remove the parenthesis at the end.
If that doesn't work, try
var tumbnailButton: UIButton {
get{
let button = UIButton(frame: thumbnailImageView.frame)
button.addTarget(self, action: #selector(tapBlurButton(_:)), for: .touchUpInside)
button.clipsToBounds = true
return button
}
}
Make this class which inherits UITapGestureRecognizer
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)
}
}
then make an extension of UIImageView or UIView
extension UIImageView {
public func addTapGesture(tapNumber: Int = 1, action: ((UITapGestureRecognizer) -> ())?) {
let tap = BlockTap(tapCount: tapNumber, fingerCount: 1, action: action)
addGestureRecognizer(tap)
isUserInteractionEnabled = true
}
}
Then You can use this as
imageView?.addTapGesture(action: {[unowned self] (_) in
//Do whatever on click of image
})
In Your code you can use this as
you can use addTapGesture to any imageview in your code like this
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
}()
on click of imageView cornerRadius of image will change to 4.0.
In my UICollectionViewCell I have an image and a label. The picture takes up the whole cell (which I want) - however, the label is placed behind the image, so it's not visible. I have tried bringSubview(toFront: titleLabel), but nothing happens... I got no clue what to do really, have done a lot of searching.
This is the code for the cell, I don't use Storyboard as you can see (sorry for messy constraints, was testing different solutions to find out if this was the problem)
import UIKit
class BaseCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
setupBasket()
}
func setupViews() {
}
func setupBasket(){
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class VideoCell: BaseCell {
var selectedItemID : String!
static let sharedInstance = VideoCell()
var video: Video? {
didSet {
titleLabel.text = video?.title
setupThumbnailImage()
}
}
func setupThumbnailImage() {
if let thumbnailImageUrl = video?.thumbnail_image_name {
thumbnailImageView.loadImageUsingUrlString(thumbnailImageUrl)
}
}
let thumbnailImageView: CustomImageView = {
let imageView = CustomImageView()
imageView.image = UIImage(named: "taylor_swift_blank_space")
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
let titleLabel: UILabel = {
let textView = UILabel()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.text = "Clothes"
textView.textColor = UIColor.lightGray
return textView
}()
let separatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
return view
}()
var titleLabelHeightConstraint: NSLayoutConstraint?
let addtoBasket = UIButton(type: .contactAdd)
override func setupViews() {
addtoBasket.frame = CGRect(x: 50, y: 0, width: 20, height: 60)
addSubview(addtoBasket)
addSubview(titleLabel)
addSubview(thumbnailImageView)
addSubview(separatorView)
addSubview(addtoBasket)
titleLabel.superview!.bringSubview(toFront: titleLabel)
//horizontal constraints
addConstraintsWithFormat("H:|-0-[v0]-0-|", views: thumbnailImageView)
//vertical constraints
addConstraintsWithFormat("V:|-1-[v0]-1-|", views: thumbnailImageView)
addConstraintsWithFormat("H:|-0-[v0]-1-|", views: separatorView)
addtoBasket.translatesAutoresizingMaskIntoConstraints = false
addtoBasket.heightAnchor.constraint(equalToConstant: 20).isActive = true
addtoBasket.widthAnchor.constraint(equalToConstant: 20).isActive = true
addtoBasket.centerXAnchor.constraint(equalTo: addtoBasket.superview!.centerXAnchor, constant: 90).isActive = true
addtoBasket.centerYAnchor.constraint(equalTo: addtoBasket.superview!.centerYAnchor, constant: -50).isActive = true
//top constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 8))
//right constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0))
//right constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 20))
//height constraint
titleLabelHeightConstraint = NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: -10)
addConstraint(titleLabelHeightConstraint!)
}
}
Try accessing the labels layer and set its zPosition.
Try titleLabel.layer.zPosition = 1
There was clearly something wrong with the constraints, now working! Thanks
I want to have several objects that I can drag and drop.
Here's my code for moving one object (with lot of help from #vacawama):
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var panView: UIView!
#IBOutlet weak var panViewCenterX: NSLayoutConstraint!
#IBOutlet weak var panViewCenterY: NSLayoutConstraint!
let panRec = UIPanGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
panRec.addTarget(self, action: "draggedView:")
panView.addGestureRecognizer(panRec)
// Do any additional setup after loading the view, typically from a nib.
}
func draggedView(sender:UIPanGestureRecognizer){
self.view.bringSubviewToFront(sender.view!)
var translation = sender.translationInView(self.view)
panViewCenterY.constant += translation.y
panViewCenterX.constant += translation.x
sender.setTranslation(CGPointZero, inView: self.view)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I want to have more objects in my project:
#IBOutlet weak var panView2: UIView!
#IBOutlet weak var panView3: UIView!
#IBOutlet weak var panView4: UIView!
...
So, what is the easiest way to implement this in such way that I can have multiple panView which I can move independently around (one at the time)?
If you are using Auto Layout, you shouldn't just move a view by altering its center. Anything that causes Auto Layout to run will move your view back to its original position.
Here is an implementation of a new class called DraggableView that works with Auto Layout to provide views that can be dragged. It creates constraints in code for the width, height, X position, and Y position of the view. It uses its own UIPanGestureRecognizer to allow the view to be dragged.
DraggableView.swift can be dropped into any project that needs draggable views. Take a look at ViewController.swift below to see how easy it is to use.
DraggableView.swift
import UIKit
class DraggableView: UIView {
let superView: UIView!
let xPosConstraint: NSLayoutConstraint!
let yPosConstraint: NSLayoutConstraint!
var constraints: [NSLayoutConstraint] {
get {
return [xPosConstraint, yPosConstraint]
}
}
init(width: CGFloat, height: CGFloat, x: CGFloat, y: CGFloat, color: UIColor, superView: UIView) {
super.init()
self.superView = superView
self.backgroundColor = color
self.setTranslatesAutoresizingMaskIntoConstraints(false)
let panGestureRecognizer = UIPanGestureRecognizer()
panGestureRecognizer.addTarget(self, action: "draggedView:")
self.addGestureRecognizer(panGestureRecognizer)
let widthConstraint = NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: width)
self.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: height)
self.addConstraint(heightConstraint)
xPosConstraint = NSLayoutConstraint(item: self, attribute: .CenterX, relatedBy: .Equal,
toItem: superView, attribute: .Leading, multiplier: 1.0, constant: x)
yPosConstraint = NSLayoutConstraint(item: self, attribute: .CenterY, relatedBy: .Equal,
toItem: superView, attribute: .Top, multiplier: 1.0, constant: y)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func moveByDeltaX(deltaX: CGFloat, deltaY: CGFloat) {
xPosConstraint.constant += deltaX
yPosConstraint.constant += deltaY
}
func draggedView(sender:UIPanGestureRecognizer){
if let dragView = sender.view as? DraggableView {
superView.bringSubviewToFront(dragView)
var translation = sender.translationInView(superView)
sender.setTranslation(CGPointZero, inView: superView)
dragView.moveByDeltaX(translation.x, deltaY: translation.y)
}
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let dragView1 = DraggableView(width: 75, height: 75, x: 50, y: 50,
color: UIColor.redColor(), superView: self.view)
self.view.addSubview(dragView1)
self.view.addConstraints(dragView1.constraints)
let dragView2 = DraggableView(width: 100, height: 100, x: 150, y: 50,
color: UIColor.blueColor(), superView: self.view)
self.view.addSubview(dragView2)
self.view.addConstraints(dragView2.constraints)
let dragView3 = DraggableView(width: 125, height: 125, x: 100, y: 175,
color: UIColor.greenColor(), superView: self.view)
self.view.addSubview(dragView3)
self.view.addConstraints(dragView3.constraints)
}
}
UPDATE:
Here is a version of DraggableView.swift that supports images as a subview.
import UIKit
class DraggableView: UIView {
let superView: UIView!
let xPosConstraint: NSLayoutConstraint!
let yPosConstraint: NSLayoutConstraint!
var constraints: [NSLayoutConstraint] {
get {
return [xPosConstraint, yPosConstraint]
}
}
init(width: CGFloat, height: CGFloat, x: CGFloat, y: CGFloat, color: UIColor, superView: UIView, imageToUse: String? = nil, contentMode: UIViewContentMode = .ScaleAspectFill) {
super.init()
self.superView = superView
self.backgroundColor = color
self.setTranslatesAutoresizingMaskIntoConstraints(false)
let panGestureRecognizer = UIPanGestureRecognizer()
panGestureRecognizer.addTarget(self, action: "draggedView:")
self.addGestureRecognizer(panGestureRecognizer)
let widthConstraint = NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: width)
self.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: height)
self.addConstraint(heightConstraint)
xPosConstraint = NSLayoutConstraint(item: self, attribute: .CenterX, relatedBy: .Equal,
toItem: superView, attribute: .Leading, multiplier: 1.0, constant: x)
yPosConstraint = NSLayoutConstraint(item: self, attribute: .CenterY, relatedBy: .Equal,
toItem: superView, attribute: .Top, multiplier: 1.0, constant: y)
if imageToUse != nil {
if let image = UIImage(named: imageToUse!) {
let imageView = UIImageView(image: image)
imageView.contentMode = contentMode
imageView.clipsToBounds = true
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(imageView)
self.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: 0))
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func moveByDeltaX(deltaX: CGFloat, deltaY: CGFloat) {
xPosConstraint.constant += deltaX
yPosConstraint.constant += deltaY
}
func draggedView(sender:UIPanGestureRecognizer){
if let dragView = sender.view as? DraggableView {
superView.bringSubviewToFront(dragView)
var translation = sender.translationInView(superView)
sender.setTranslation(CGPointZero, inView: superView)
dragView.moveByDeltaX(translation.x, deltaY: translation.y)
}
}
}
The way a gesture recognizer works is that you attach it to a view. So if you have multiple views, and you want them to be draggable in the same way, attach a different pan gesture recognizer to each one.
Now let's say you want them all to have the same action handler. No problem. In the action handler, you receive the current gesture recognizer as a parameter. It has a view property; that's the view it is attached to! So now you know that that's the view you're moving.
Finally:
Found this example which explained it in a easy way:
http://www.raywenderlich.com/76020/using-uigesturerecognizer-with-swift-tutorial
So, now multiple Pan's are working..
Here's the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var boxToMove1: UIView!
#IBOutlet weak var boxToMove2: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func handlePan(objectToMove:UIPanGestureRecognizer) {
let translation = objectToMove.translationInView(self.view)
objectToMove.view!.center = CGPoint(x: objectToMove.view!.center.x + translation.x, y: objectToMove.view!.center.y + translation.y)
objectToMove.setTranslation(CGPointZero, inView: self.view)
println("\(objectToMove.view!.tag)") //Verify correct object received
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I linked up the "Pan Gesture Recognizer" from the "Object library" to each boxToMove. Then I linked the "Pan Gesture Recognizer" (both) to my #IBAction func handlePan...
This is now working!!!
Finally I understand the way this Gesture Recognizer is working!
What I'm still trying to figure out is how to do all this linking programmatically.. Any idea?