从另一个视图控制器

时间:2016-01-05 18:49:28

标签: ios swift uibutton

我正在使用此代码在我的主ViewController上自定义UIButtons并将其放在它自己独立的.swift文件中,以便在存在UIButton的任何地方引用它。我希望能够在按下按钮后从我的主ViewController中修改MyCustomButton的属性。 例如,我按下一个使用MyCustomButton属性及其颜色变化的按钮。

我只是快速进入并且我对它的来龙去不是很熟悉。任何帮助表示赞赏。

import Foundation
import UIKit

class MyCustomButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.layer.cornerRadius = 25;
        self.layer.borderColor = UIColor.blackColor().CGColor
        self.layer.borderWidth = 3
        self.backgroundColor = UIColor.redColor()
        self.tintColor = UIColor.whiteColor()
        self.setTitle("", forState: UIControlState.Normal)
        self.titleLabel?.numberOfLines = 0
        self.titleLabel?.textAlignment = NSTextAlignment.Center
    }
}

3 个答案:

答案 0 :(得分:0)

您可以尝试覆盖layoutSubviews方法:

override func layoutSubviews() {
    super.layoutSubviews()

    if self.state == UIControlState.Highlighted {
        // DO WHAT YOU WANT
    } else {
        // RESET TO NORMAL
    }
}

答案 1 :(得分:0)

KVOdelegate protocolSwift)可行!这些中的任何一个都允许您在发生特定操作时操纵UI元素的属性。

答案 2 :(得分:0)

如果要创建新类并更改按钮默认行为,则应覆盖此类函数

//Put this button code next to your button (or span mimicking button) that adds files to the queue.
<button id="upload_all" type="submit" class="btn btn-primary start">
    <i class="glyphicon glyphicon-upload"></i>
    <span>Start upload</span>
</button>

//Give your buttons a class and set their display to none.
var uploadButton = $('<button/>', { 
                       class:"upload", 
                       style:"display:none" 
                   })
                   .on('click', function () {
                        var $this = $(this),
                        data = $this.data();
                        data.submit().always(function () {      
                            $this.remove();
                        });
                   });

//Bind their click to the click of your upload_all button. 
$('#upload_all').on('click', function() {
     $('.upload').click();
});

但是如果您只想在按钮点击上更改按钮属性,可以在按钮回调方法上执行此操作:

override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
    super.pressesBegan(presses, withEvent: event)
    // add your implementation here
}

//    func pressesCancelled
//    func pressesChanged
//    func pressesEnded
//    etc.