Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 调整动画大小后,UIButton不尊重Aspect Fill contentMode_Ios_Swift_Ios8 - Fatal编程技术网

Ios 调整动画大小后,UIButton不尊重Aspect Fill contentMode

Ios 调整动画大小后,UIButton不尊重Aspect Fill contentMode,ios,swift,ios8,Ios,Swift,Ios8,我正在使用自动布局。以下是视图的初始状态 中间是一个包含在视图中的按钮。按钮具有contentMode Aspect Fill,并且图像被设置为按钮的背景图像 然后,我使用以下代码转换视图,这将放大中心卡以填充屏幕,并将图像移动到视图顶部: cardTrailingSpaceConstraint.constant = 0 cardLeadingSpaceConstraint.constant = 0 cardView.removeConstraint(cardAspectRatioConstr

我正在使用自动布局。以下是视图的初始状态

中间是一个包含在视图中的按钮。按钮具有contentMode Aspect Fill,并且图像被设置为按钮的背景图像

然后,我使用以下代码转换视图,这将放大中心卡以填充屏幕,并将图像移动到视图顶部:

cardTrailingSpaceConstraint.constant = 0
cardLeadingSpaceConstraint.constant = 0
cardView.removeConstraint(cardAspectRatioConstraint)
let cardHeightConstraint = NSLayoutConstraint(item: cardView, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1.0, constant: 0)
view.addConstraint(cardHeightConstraint)

dishImageButton.removeConstraint(dishButtonBottomSpaceConstraint)
let dishButtonHeightConstraint = NSLayoutConstraint(item: dishImageButton, attribute: .Height, relatedBy: .Equal, toItem: cardView, attribute: .Height, multiplier: 0.2, constant: 0)
cardView.addConstraint(dishButtonHeightConstraint)

cardView.setNeedsUpdateConstraints()
UIView.animateWithDuration(0.7, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: nil, animations: { [unowned self] () -> Void in
    self.cardHeader.alpha = 0
    self.cardView.layer.cornerRadius = 0
    self.cardView.layoutIfNeeded()

    }) { [unowned self] (finished) -> Void in

        }
结果是:

然而,这不是我想要的。该按钮不符合contentMode,因此图像会被拉伸

有人能告诉我如何维护按钮的Aspect Fill contentMode吗

  • 将按钮类型设置为
    uibuttonypecustom
    (“脚本或xib中的自定义”)
  • 设置按钮的图像,而不是按钮的背景图像
  • viewDidLoad
    中,将
    按钮.imageView.contentMode
    设置为
    UIViewContentMode.ScaleAspectFill

  • Swift 2.x版本:

    let myButton = UIButton(type: .Custom)
    myButton.frame = CGRectMake(0, 0, 200, 20)
    myButton.backgroundColor = UIColor.blackColor()
    myButton.imageView.contentMode = .ScaleAspectFill // ALTERNATIVE:  .ScaleAspectFit
    myButton.setImage(UIImage(named: "myImageName"), forState: .Normal)
    myButton.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
    view.addSubview(myButton)
    
    斯威夫特2

    button.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
    
    所有内容模式:

      .ScaleToFill
       .ScaleAspectFit
       .ScaleAspectFill
       .Redraw 
       .Center 
       .Top
       .Bottom
       .Left
       .Right
       .TopLeft
       .TopRight
       .BottomLeft
       .BottomRight
    

    Swift 3


    从Rob的回答开始:

        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 30))
        btn.setImage(UIImage(named: "albumsBtn"), for: UIControlState.normal)
        btn.imageView?.contentMode = UIViewContentMode.scaleAspectFit
        btn.addTarget(self.navigationController, action: #selector(CustomGalleryViewController.showAlbums(_:)), for:  UIControlEvents.touchUpInside)
        let item = UIBarButtonItem(customView: btn)
        self.navigationItem.leftBarButtonItem = item
    
    Swift 4.2 扩展

    更新:这个和其他答案在ios 11中对我不起作用。最接近的答案是@Jaro,但我认为最好制作一个UIImageView并在其上添加一个按钮,或者创建一个自定义的UIImageView类,该类将有一个手势识别器并单击动画。

    可能对某人有所帮助

    button.subviews.first?.contentMode = .scaleAspectFit
    

    请在[btn setImage:forState:][/strong>用法之前尝试此操作:

        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
        btn.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
    
    • 斯威夫特4

    您可以对按钮进行子类化并添加以下内容:

    class FitButton: UIButton {
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
    
    
        }
    
        override func layoutSubviews() {
            self.imageView?.contentMode = .scaleAspectFill
            self.contentHorizontalAlignment = .fill
            self.contentVerticalAlignment = .fill
            super.layoutSubviews()
    
    
        }
    
    }
    

    在Xcode 10.1中,您可以使用interface builder。在右侧的属性检查器中,按如下方式使用控制部分:


    这种语言似乎有了更新

    为了获得xscoder解决方案,我必须深入挖掘:

    myButton.imageView.contentMode = .ScaleAspectFill 
    
    更新版本如下:

    myButton.imageView?.contentMode=UIView.contentMode.scalespectfit
    Swift

    for按钮具有contentMode方面填充:

    btn.contentHorizontalAlignment = .fill
    btn.contentVerticalAlignment = .fill
    btn.imageView?.contentMode = .scaleAspectFill
    

    当我使用BarButtonItem的自定义按钮时,这个解决方案对我有效

    1.正在从服务器加载图像
    2.裁剪图像
    3.设置按钮的图像

    以下是裁剪图像的功能:

    extension UIImage {
      func crop(to:CGSize) -> UIImage {
        guard let cgimage = self.cgImage else { return self }
    
        let contextImage: UIImage = UIImage(cgImage: cgimage)
    
        let contextSize: CGSize = contextImage.size
    
        //Set to square
        var posX: CGFloat = 0.0
        var posY: CGFloat = 0.0
        let cropAspect: CGFloat = to.width / to.height
    
        var cropWidth: CGFloat = to.width
        var cropHeight: CGFloat = to.height
    
        if to.width > to.height { //Landscape
            cropWidth = contextSize.width
            cropHeight = contextSize.width / cropAspect
            posY = (contextSize.height - cropHeight) / 2
        } else if to.width < to.height { //Portrait
            cropHeight = contextSize.height
            cropWidth = contextSize.height * cropAspect
            posX = (contextSize.width - cropWidth) / 2
        } else { //Square
            if contextSize.width >= contextSize.height { //Square on landscape (or square)
                cropHeight = contextSize.height
                cropWidth = contextSize.height * cropAspect
                posX = (contextSize.width - cropWidth) / 2
            }else{ //Square on portrait
                cropWidth = contextSize.width
                cropHeight = contextSize.width / cropAspect
                posY = (contextSize.height - cropHeight) / 2
            }
        }
    
        let rect: CGRect = CGRect(x : posX, y : posY, width : cropWidth, height : cropHeight)
    
        // Create bitmap image from context using the rect
        let imageRef: CGImage = contextImage.cgImage!.cropping(to: rect)!
    
        // Create a new image based on the imageRef and rotate back to the original orientation
        let cropped: UIImage = UIImage(cgImage: imageRef, scale: self.scale, orientation: self.imageOrientation)
    
        cropped.draw(in: CGRect(x : 0, y : 0, width : to.width, height : to.height))
    
        return cropped
      }
    }
    
    扩展UIImage{ func裁剪(到:CGSize)->UIImage{ guard let cgimage=self.cgimage else{return self} 让contextImage:UIImage=UIImage(cgImage:cgImage) 让contextSize:CGSize=contextImage.size //摆正 var posX:CGFloat=0.0 变量posY:CGFloat=0.0 让CropSpect:CGFloat=to.width/to.height 变量cropWidth:CGFloat=to.width 变量cropHeight:CGFloat=to.height 如果to.width>to.height{// cropWidth=contextSize.width cropHeight=contextSize.width/cropspect posY=(contextSize.height-cropHeight)/2 }否则,如果to.width=contextSize.height{//横向正方形(或正方形) cropHeight=contextSize.height cropWidth=contextSize.height*CropSpect posX=(contextSize.width-cropWidth)/2 }else{//肖像上的正方形 cropWidth=contextSize.width cropHeight=contextSize.width/cropspect posY=(contextSize.height-cropHeight)/2 } } 设rect:CGRect=CGRect(x:posX,y:posY,宽度:cropWidth,高度:cropHeight) //使用rect从上下文创建位图图像 让imageRef:CGImage=contextImage.CGImage!。裁剪(到:rect)! //基于imageRef创建新图像并旋转回原始方向 让裁剪:UIImage=UIImage(cgImage:imageRef,比例:self.scale,方向:self.imageOrientation) 裁剪的.draw(in:CGRect(x:0,y:0,宽度:到.width,高度:到.height)) 复种 } }
    Swift 5.0
    带有
    的自定义
    ui按钮的代码

    var mainImageButton : UIButton = {
        var imageButton = UIButton()
        imageButton.translatesAutoresizingMaskIntoConstraints = false
        imageButton.contentMode = .scaleAspectFit
        imageButton.backgroundColor = .white
        imageButton.layer.cornerRadius = 80 / 2
    
        // The short way
        imageButton.contentMode = .scaleAspectFit
    
        // The long way
        imageButton.imageView?.contentMode = UIView.ContentMode.scaleAspectFill
    
        imageButton.clipsToBounds = true
        return imageButton
    }()
    

    为我工作。请记住,在#3上,将其绑定到IBOutlet以获得正确的按钮。这非常有效,但现在我遇到了约束问题。如何将目标约束到图像按钮,而不是背景按钮图像?在Swift 5.2上工作。我的问题是我设置的是背景图像而不是图像。谢谢肯定对我来说,直到我自定义了类型,它才起作用。谢谢。您应该在扩展行中添加@IBDesignable,这样它才能在接口生成器Wift 4.2扩展UIButton{///0=>。ScaleToFill///1=>。scaleSpectFit///2=>。scaleSpectFill@IBInspectable var imageContentMode:Int{get{return self.imageView?.contentMode.rawValue??0}设置{if let mode=UIView.ContentMode(rawValue:newValue),self.imageView!=nil{self.imageView?.ContentMode=mode}}
    extension UIImage {
      func crop(to:CGSize) -> UIImage {
        guard let cgimage = self.cgImage else { return self }
    
        let contextImage: UIImage = UIImage(cgImage: cgimage)
    
        let contextSize: CGSize = contextImage.size
    
        //Set to square
        var posX: CGFloat = 0.0
        var posY: CGFloat = 0.0
        let cropAspect: CGFloat = to.width / to.height
    
        var cropWidth: CGFloat = to.width
        var cropHeight: CGFloat = to.height
    
        if to.width > to.height { //Landscape
            cropWidth = contextSize.width
            cropHeight = contextSize.width / cropAspect
            posY = (contextSize.height - cropHeight) / 2
        } else if to.width < to.height { //Portrait
            cropHeight = contextSize.height
            cropWidth = contextSize.height * cropAspect
            posX = (contextSize.width - cropWidth) / 2
        } else { //Square
            if contextSize.width >= contextSize.height { //Square on landscape (or square)
                cropHeight = contextSize.height
                cropWidth = contextSize.height * cropAspect
                posX = (contextSize.width - cropWidth) / 2
            }else{ //Square on portrait
                cropWidth = contextSize.width
                cropHeight = contextSize.width / cropAspect
                posY = (contextSize.height - cropHeight) / 2
            }
        }
    
        let rect: CGRect = CGRect(x : posX, y : posY, width : cropWidth, height : cropHeight)
    
        // Create bitmap image from context using the rect
        let imageRef: CGImage = contextImage.cgImage!.cropping(to: rect)!
    
        // Create a new image based on the imageRef and rotate back to the original orientation
        let cropped: UIImage = UIImage(cgImage: imageRef, scale: self.scale, orientation: self.imageOrientation)
    
        cropped.draw(in: CGRect(x : 0, y : 0, width : to.width, height : to.height))
    
        return cropped
      }
    }
    
    var mainImageButton : UIButton = {
        var imageButton = UIButton()
        imageButton.translatesAutoresizingMaskIntoConstraints = false
        imageButton.contentMode = .scaleAspectFit
        imageButton.backgroundColor = .white
        imageButton.layer.cornerRadius = 80 / 2
    
        // The short way
        imageButton.contentMode = .scaleAspectFit
    
        // The long way
        imageButton.imageView?.contentMode = UIView.ContentMode.scaleAspectFill
    
        imageButton.clipsToBounds = true
        return imageButton
    }()