【问题标题】:how to make circular image that is in button in swift? [duplicate]如何快速制作按钮中的圆形图像? [复制]
【发布时间】:2019-07-03 11:21:46
【问题描述】:

我在UIViewcontroller 中有一个按钮,其中包含带有名称和图像的按钮。 我想在此按钮 [NOT Whole BUTTON] 中制作UIImageView 圆形。

有什么办法吗?

这是当前状态的截图:

我想要的是:


“类似问题”(与我的不同):

How can I set UIButton image, which Image is round shape with a border

我不希望图像视图的边框,并且我在情节提要中采用了按钮,只想使图像成为圆形(没有边框任何边框)。

很明显,为什么我的问题被标记为重复的问题只是将边框设置为按钮而不是 UIImageView 循环。

他要求以编程方式创建按钮并设置边框,以便按钮看起来是圆形的,而且答案不被接受,没有一个答案对我有用。

我想指出,如您所见,我已接受以下答案之一,该人已按照我的预期给出了答案。

还因为它在导航栏中导致更改按钮的大小,但因为答案没有给我像这个问题这样的错误

How to create a circular button in Swift?

对于那些为圆形按钮标记重复的人,我不希望按钮是圆形的。


【问题讨论】:

    标签: ios swift uibutton


    【解决方案1】:

    button.imageView'scornerRadius设置为viewDidLayoutSubviews()button's的一半height,即

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: button.bounds.width - button.bounds.height)
        button.imageView?.layer.cornerRadius = button.bounds.height/2.0
    }
    

    我已经设置了buttonimageEdgeInsets,所以你可以得到精确的循环image

    【讨论】:

    • 但不是在 viewDidLayoutSubviews() 中设置代码,而是在 viewdidload() 中设置,这有什么不同吗?
    • 您不会在viewDidLoad() 中得到正确的framebutton。这就是我在viewDidLayoutSubviews() 中添加代码的原因。您也可以将其移至viewDidAppear(_:animated:)
    • 但我得到了我需要的确切输出,所以如果我在 viewDidLayoutSubviews() 中添加代码,你会建议什么
    • 这是因为您可能使用与故事板中相同的模拟器。这就是为什么它可能会采用相同的帧。
    【解决方案2】:

    我建议创建一个自定义按钮并将 UIImageView 添加为子视图,设置正确的大小并设置layer.cornerRadius = height/2

    【讨论】:

      【解决方案3】:

      斯威夫特 4.2:

      let image = UIImage(named: "imageName")
      imageView.layer.borderWidth = 1.0
      imageView.layer.masksToBounds = false
      imageView.layer.borderColor = UIColor.white.cgColor
      imageView.layer.cornerRadius = image.frame.size.width / 2
      imageView.clipsToBounds = true
      

      【讨论】:

      • OP 指定图像在按钮内,这不考虑这一点。
      猜你喜欢
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 2017-03-04
      • 1970-01-01
      相关资源
      最近更新 更多