gpt4 book ai didi

ios - 自定义类 View 和选择器引用

转载 作者:行者123 更新时间:2023-11-29 00:48:51 24 4
gpt4 key购买 nike

我正在制作一个自定义类,它只具有一些基本功能,一旦该类在任何 viewController 中初始化,我就可以重用它。问题是我不知道如何引用 View 或 #selector 中调用的任何函数,并且收到错误:使用未解析的标识符“ View ”。有人知道这是怎么做到的吗?下面的示例是创建一个新的 UIButton。

import Foundation
import UIKit

class Utils {

var newUpdatesBtn: UIButton!

func setupButtonNewUpdates() {
newUpdatesBtn = UIButton(type: UIButtonType.System) // .System
newUpdatesBtn.setTitle("New Updates", forState: UIControlState.Normal)
newUpdatesBtn.bounds = CGRect(x: 0, y: 0, width: 123, height: 27)
newUpdatesBtn.center = CGPoint(x: view.bounds.width / 2, y: 90) // 80 point button, 20 point status bar, 40 point half button, 8 point margins
newUpdatesBtn.setBackgroundImage(UIImage(named: "new-updates"), forState: UIControlState.Normal)
newUpdatesBtn.titleLabel?.font = UIFont.systemFontOfSize(14)
newUpdatesBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
newUpdatesBtn.addTarget(self, action: #selector(newUpdatesButtonPressed), forControlEvents: UIControlEvents.TouchUpInside)
self.newUpdatesBtn.alpha = 0;
self.navigationController!.view.addSubview(newUpdatesBtn)
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.newUpdatesBtn.alpha = 1;
})
}

}

(问题行)

View .bounds.width

newUpdatesBtn.addTarget(self, action: #selector(newUpdatesButtonPressed), forControlEvents: UIControlEvents.TouchUpInside)

最佳答案

这是因为您没有在 View 属性中设置任何引用。你可以这样做:

func setupButtonNewUpdates(targetView:UIView)
{
newUpdatesBtn = UIButton(type: UIButtonType.System) // .System
.
.
.
newUpdatesBtn.center = CGPoint(x: targetView.bounds.width / 2, y: 90) // 80 point button, 20 point status bar, 40 point half button, 8 point margins
.
.
.
targetView.addSubView(newUpdatesBtn);
}

现在,无论何时从任何 View Controller 调用此方法,只需传递该 VC 的 View 即可。例如:

var util:Utils = new Utils();
util.setupButtonNewUpdates(self.view);

关于ios - 自定义类 View 和选择器引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38365635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com