【问题标题】:Toggle UIButton Image切换 UIButton 图像
【发布时间】:2020-10-01 07:55:32
【问题描述】:

我正在尝试创建一个UIButton,当你不关注某事时它会显示文本,但当你关注时它会在右侧显示文本和复选标记。

我已经能够使用以下方法实现这一点 -

  private(set) var followButton = UIButton(type: .system)

.....

  func setFollowButtonText() {
    let text: String = isFollowing ? "Following" : "Follow"
    let image: UIImage? = isFollowing ? UIImage(systemName: "checkmark") : nil
    followButton.setTitle(text, for: .normal)
    followButton.setImage(image, for: .normal)
    followButton.imageToRight()
  }

.....

extension UIButton {
  func imageToRight() {
      transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
      titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
      imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
  }
}

但是在切换状态时,添加了复选标记然后移动位置,它不平滑并且似乎略微向右跳跃。

如何防止这种行为?我希望图像能够平滑地动画到该最终位置,或者出现在该最终位置并避免跳跃。

【问题讨论】:

  • 可以在字符串中使用 unicode 复选标记吗?

标签: ios swift uibutton uiimage cgaffinetransform


【解决方案1】:

您可能希望为按钮设置足够高的高度限制,以便在切换复选标记时标签不会向上/向下移动。

为了避免尴尬的动画:

extension UIButton {
    func imageToRight() {
        UIView.setAnimationsEnabled(false)
        transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
        titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
        imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
        UIView.setAnimationsEnabled(true)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 2020-09-05
    • 2011-07-03
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多