Ios 从另一个视图控制器修改类
我正在使用此代码自定义主ViewController上的UIButtons,并将其放置在它自己单独的.swift文件中,以便在UIButton存在的任何位置引用。按下按钮后,我希望能够从主ViewController中修改MyCustomButton的属性。 例如,我按下一个使用MyCustomButton属性的按钮,它的颜色会发生变化 我刚刚进入swift,还不太熟悉它的来龙去脉。感谢您的帮助Ios 从另一个视图控制器修改类,ios,swift,uibutton,Ios,Swift,Uibutton,我正在使用此代码自定义主ViewController上的UIButtons,并将其放置在它自己单独的.swift文件中,以便在UIButton存在的任何位置引用。按下按钮后,我希望能够从主ViewController中修改MyCustomButton的属性。 例如,我按下一个使用MyCustomButton属性的按钮,它的颜色会发生变化 我刚刚进入swift,还不太熟悉它的来龙去脉。感谢您的帮助 import Foundation import UIKit class MyCustomButt
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
}
}
您可以尝试覆盖layoutSubviews方法:
override func layoutSubviews() {
super.layoutSubviews()
if self.state == UIControlState.Highlighted {
// DO WHAT YOU WANT
} else {
// RESET TO NORMAL
}
}
或者()就行了!这两种方法都允许您在特定操作发生时操作UI元素的属性。如果您想创建新类并更改按钮默认行为,您应该重写类似于此的函数
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.
检查该问题:
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 100)
button.setTitle("My Button", forState: UIControlState.Normal)
button.addTarget(self, action: "someAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
}
func someAction(sender: UIButton) {
print("My Button tapped")
sender.setTitle("Now Tapped", forState: UIControlState.Normal)
}