Swift 编程 UIButtons

标签 swift uibutton system self

我对 swift 语言比较陌生,我在创建按钮时遇到了困难。我创建了一个新文件作为 UIButton,那么如何使用“self”更改按钮类型?

例如..

import UIKit

class LoginButton: UIButton {
    override init(frame: CGRect){

        super.init(frame: frame)


        self.buttonWithType(UIButtonType.System) as UIButton
// Above is where I need the button type as "System"

        self.enabled = true
        self.setTitle("Log in", forState: UIControlState.Normal)
        self.addTarget(self, action: "logInPressed", forControlEvents:    UIControlEvents.TouchUpInside)


    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func logInPressed(){
        println("log in")
    }

}

最佳答案

你真的需要继承 UIButton 吗?在大多数用例中,人们会直接使用 UIButton 而不会对其进行子类化。

您引用的 buttonWithType() 方法是类方法(不是实例方法)。您将其称为 UIButton.buttonWithType(type) ,它返回如此配置的 UIButton 的实例。实例化按钮后不能更改类型;但是,有几种方法可用于在实例化后修改按钮的外观。

要为按钮添加大小为 2.0 的棕色边框,您可以添加以下代码:

    myButton.layer.borderColor = UIColor.brownColor().CGColor
    myButton.layer.borderWidth = 2.0

关于Swift 编程 UIButtons,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28842261/

相关文章:

ios - UIButton背景图像与图像

powershell - 检查程序是否正在通过可执行路径运行

java - GetPropertyAction 与 System.getProperty 获取系统变量

xcode - 是否可以使 @IBDesignable 覆盖 Interface Builder 值?

ios - 在多个 ViewController 之间访问/传递公共(public)数据

ios - 如何以编程方式为 UIButton 添加系统图标?

c - 等待 system() 调用完成

iOS - UISlider 滑动时显示多个值

arrays - 使用函数从 TextView 数组中退出第一响应者

ios - 带约束的 UIButton 显示中心 (500,500)