【问题标题】:Modify class from another view controller从另一个视图控制器修改类
【发布时间】:2016-01-05 18:49:27
【问题描述】:

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

我刚刚开始接触 swift,还不太熟悉它的来龙去脉。任何帮助表示赞赏。

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
    }
}

【问题讨论】:

标签: ios swift uibutton


【解决方案1】:

你可以尝试覆盖 layoutSubviews 方法:

override func layoutSubviews() {
    super.layoutSubviews()

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

【讨论】:

    【解决方案2】:

    KVOdelegate protocol (Swift) 会起作用!当特定操作发生时,其中任何一个都允许您操纵 UI 元素的属性。

    【讨论】:

      【解决方案3】:

      如果你想创建新类并改变按钮默认行为,你应该重写这样的函数

      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)
          }
      

      【讨论】:

        猜你喜欢
        • 2012-04-02
        • 1970-01-01
        • 2018-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-02
        • 1970-01-01
        相关资源
        最近更新 更多