【问题标题】:Subclass of UIButton with rounded corners (swift)带有圆角的 UIButton 的子类(swift)
【发布时间】:2015-11-23 15:57:45
【问题描述】:

使用 swift,我想创建一个带圆角的按钮。为了使其可重用,我的偏好是继承 UIButton,并提出以下内容:

import Foundation
import UIKit

class LoginButton: UIButton {

  let corner_radius : CGFloat =  4.0

  override func drawRect(rect: CGRect) {
    super.drawRect(rect)
    self.layer.cornerRadius = corner_radius
  }

}

不幸的是,这似乎并没有像我希望的那样工作,即使它编译得很好。也许我错过了一些东西 - 我对此很陌生!

有什么想法吗?

【问题讨论】:

    标签: swift uibutton subclass


    【解决方案1】:

    您需要使用clipsToBounds 确保包含视图不会绘制在圆角半径上:

    self.clipsToBounds = true
    

    【讨论】:

    • 谢谢 - maskToBounds 和 clipsToBounds 有什么区别?
    • 它们本质上是一样的,我只是在使用cornerRadius时倾向于使用clipsToBounds
    【解决方案2】:

    您还需要打开图层上的masksToBounds

    self.layer.masksToBounds = true
    

    【讨论】:

      猜你喜欢
      • 2016-09-06
      • 2013-10-14
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 2020-10-25
      • 2011-10-07
      相关资源
      最近更新 更多