ios - 在新 Controller 标题中传递了 UIButton AttributeTitle

标签 ios swift

我想问一下如何将 UIButton 中的 attributeTitle 传递到新的 Controller 导航标题中。我有 3 个按钮,设置准确,这是我的代码。

let fiqhButton: UIButton = {
    let button = UIButton(type: .system)
    let attributeText = NSAttributedString(string: "Fiqh", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 60), NSAttributedString.Key.foregroundColor: UIColor.white])
    button.setAttributedTitle(attributeText, for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.setBackgroundImage(#imageLiteral(resourceName: "milada-vigerova-36934-unsplash").withRenderingMode(.alwaysOriginal), for: .normal)
    button.clipsToBounds = true
    button.tag = 1
    button.addTarget(self, action: #selector(handlePushVC), for: .touchUpInside)
    return button
}()

这是我的 handlePushVC

@objc fileprivate func handlePushVC() {
    let layout = UICollectionViewFlowLayout()
    let searchVideoController = SearchVideoController(collectionViewLayout: layout)
    navigationController?.pushViewController(searchVideoController, animated: true)
}

谢谢

最佳答案

您可以从您的 handlePushVC 获取按钮功能,或简单地通过调用 self.fightButton .如果你想做第一个选项,你可以像这样改变你的目标:

button.addTarget(self, action: #selector(self.handlePushVC(_:)), for: .touchUpInside)

然后在您的函数中,您可以获得发送者/按钮的属性标题,并将其传递给您的 Controller 以进行推送:

@objc func handlePushVC(_ button: UIButton) {
    let layout = UICollectionViewFlowLayout()
    let searchVideoController = SearchVideoController(collectionViewLayout: layout)
    searchVideoController.title = button.attributedTitle(for: .normal)
    navigationController?.pushViewController(searchVideoController, animated: true)
}

如您所见,我们正在传递 button.attributedTitle(for: .normal) , 所以你需要做一个可选属性 NSAttributedString?那里。

最后,在您的 SearchVideoController 中的 viewDidLoad() ,您使用这个简短的函数将该变量分配给您的导航标题:

/// Sets the title with attributed string
public func setAttributedTitle(_ title: String, color: UIColor, font: UIFont) {

    let titleLabel = UILabel()
    let attributes = [NSAttributedString.Key.foregroundColor: color,
                      NSAttributedString.Key.font : font as Any]
    titleLabel.attributedText = NSAttributedString(string: title, attributes: attributes)
    titleLabel.sizeToFit()
    self.navigationItem.titleView = titleLabel
}

希望对您有所帮助!

关于ios - 在新 Controller 标题中传递了 UIButton AttributeTitle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53039642/

相关文章:

swift - 尝试通过滚动到底部来为表格 View 加载新项目

ios - 通过 TabBar 转至 VC

swift - 使用 Pods IOS 的 PubNub DDFileLogger 和 DDLog 警告

swift - 如何从 XIB 文件加载自定义创建的 View 并添加到 StackView

ios - 在 View Controller 之间插入转换时保持 View

swift - UITableView重新加载数据循环

ios - 如何从 UITableViewDelegate 的 didSelectRowtAtIndexPath 方法显示 UINavigationController?

iphone - 当帖子中的链接被点击时,Facebook iPhone 应用程序打开 App Store 应用程序而不是网页

ios - 为什么约束更改或动画不需要调用setNeedsUpdateConstraints?

ios - 如何检测和显示我当前位置附近的可用 wifi 网络?