【问题标题】:Button background Image in swift 3swift 3中的按钮背景图像
【发布时间】:2017-04-07 07:12:08
【问题描述】:

我将 背景图片 添加到 swift 中的按钮。实际图片尺寸为 100x100。这个想法是,当我单击图像时,会出现更改个人资料图像的弹出窗口。然后,您可以从图库中选择照片并保存。
保存照片后,图像完全显示。但是,问题是在我从图库中选择照片之前,我设置了默认图像。请参阅以下屏幕截图。

个人资料女性图片应与背景绿色一样大。这是我的代码。

let img = UIImage(data: match.value(forKey: "imageData") as! Data )
btnProfile.frame = CGRect(x: 10, y: 100, width: 100, height: 100)
btnProfile.imageView?.contentMode = UIViewContentMode.scaleToFill
btnProfile.setImage(img, for: UIControlState.normal)

if(user_gender == "Female"){

      btnProfile.setImage(UIImage(named: "femaleprofile_image")?.withRenderingMode(.alwaysOriginal), for: .normal)
      btnProfile.imageView?.contentMode = UIViewContentMode.scaleToFill
}

图片尺寸为 1@-> 40x40 像素和 2@-> 80x80像素。
请任何人帮助我如何解决这个问题。

【问题讨论】:

标签: ios swift3 uibutton imagebutton


【解决方案1】:

您不应在此处设置默认图像。您应该已经有了 UIImagePickerControllerDelegate,因为您正在打开照片库,您所要做的就是添加协议函数 imagePickerController didFinishPickingMediaWithInfo

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    // if user has selected an image from gallery use that
    if let profileImage = info[UIImagePickerControllerEditedImage] as UIImage {
           // use the selected image from gallery here
           btnProfile.setImage(profileImage, for: .normal)
        } else {
           // else use your logic
           let img = UIImage(data: match.value(forKey: "imageData") as! Data )
                btnProfile.frame = CGRect(x: 10, y: 100, width: 100, height: 100)
                btnProfile.imageView?.contentMode = UIViewContentMode.scaleToFill
                btnProfile.setImage(img, for: UIControlState.normal)

           if(user_gender == "Female"){
              btnProfile.setImage(UIImage(named:"femaleprofile_image")?.withRenderingMode(.alwaysOriginal), for: .normal)
              btnProfile.imageView?.contentMode = UIViewContentMode.scaleToFill
           }

    }
}

【讨论】:

  • 兄弟@khalidAfridi,请让我解释一下我的应用程序是如何工作的。当您第一次运行该应用程序时,该应用程序会询问您的性别状态。如果您单击女性图像,则会在其中显示女性图像。像上面的截图图像。然后,如果您想添加您的图片,只需点击女性图片并从您的图库中选择照片。这就是我的应用程序的工作方式。
  • @MayPhyu 我认为我的回答仍然有效。也许我不太明白,或者你不能清楚地解释你的问题,如果用户选择了一张照片,你想更改按钮图像,否则它不应该
  • 兄弟,我现在可以解决了。这是我添加的代码。 btnProfile.contentHorizo​​ntalAlignment = .fill btnProfile.contentVerticalAlignment = .fill
猜你喜欢
  • 2017-01-31
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
  • 1970-01-01
  • 2020-08-16
相关资源
最近更新 更多