【问题标题】:Creating UIButton in Xcode with icon on right side and text on left side在 Xcode 中创建 UIButton,右侧为图标,左侧为文本
【发布时间】:2021-02-17 09:46:24
【问题描述】:

我正在尝试在 Swift 中创建一个UIButton,其中标签距左侧 20 像素,图标(SF 符号)距右侧 20 像素,请参阅附图。

【问题讨论】:

  • 那么你使用的是 UIKit 还是 SwiftUI?
  • 我正在使用 UIKit 很抱歉造成混淆

标签: swift xcode button uibutton label


【解决方案1】:

我为您创建了这个自定义类(在声明按钮时,编写 Covid19Button 而不是 UIButton 以便使用它)。


class Covid19Button: UIButton {
   //declare here the objects or variables you want in your custom object
    var label: UILabel!
    var image: UIImageView!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
       commonInit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
     commonInit()
    }
    
    func commonInit(){
//Set your objects' frame and other stuff like colors ecc note that here I set random dimensions. The x should be ok however. You can change them as you prefer 
        label = UILabel(frame: CGRect(x: 20, y: 20, width: 100, height: frame.height-40))
        image = UIImageView(frame: CGRect(x: frame.width-20-image.frame.width, y: 20, width: 50, height: frame.height-40))
        
        addSubview(label)
        addSubview(image)
        
    }
    
}


【讨论】:

  • 我将代码放在我的 .swift 文件中,并为按钮“Covid19Button”添加了一个类名,但它不起作用
  • 什么意思?不符合您的预期还是什么?
  • 好吧,当我运行应用程序时,按钮保持正常,没有任何格式
  • 您是在故事板上还是以编程方式进行?如果您在情节提要上,则在情节提要上设置课程(选择按钮并继续进行身份检查器,然后在您阅读课程的地方写入Covid19Button )和类似@IBOutlet weak var btn: Covid19Button!的代码。
猜你喜欢
  • 2018-08-04
  • 2012-02-06
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
  • 2014-09-02
  • 1970-01-01
  • 2021-05-12
  • 1970-01-01
相关资源
最近更新 更多